Int32.ToString() too slow
本文关键字:too slow ToString Int32 | 更新日期: 2023-09-27 18:10:57
我有以下位置类:
public struct Pos
{
public int x;
public int y;
public float height;
public Pos (int _x, int _y, float _height)
{
x = _x;
y = _y;
height = _height;
}
public override string ToString ()
{
return x.ToString() + "," + y.ToString();
}
}
但是由于我调用Pos.ToString()
数千次,这对我来说太慢了。我所需要的是一种有效的方法来获得基于Pos.x
和Pos.y
的单个唯一值,用作字典键。注意:我不能使用Pos
,因为我只是在x
和y
上比较Pos
的不同实例。
我所需要的是一个有效的方法来获得一个唯一的值post .x和post .y,用作字典键。
不要使用ToString
作为生成唯一字典键的方式,而是实现IEquatable<Pos>
。这样,您根本不需要分配任何字符串来度量相等性:
public struct Pos : IEquatable<Pos>
{
public int X { get; private set; }
public int Y { get; private set; }
public float Height { get; private set; }
public Pos(int x, int y, float height)
{
X = x;
Y = y;
Height = height;
}
public bool Equals(Pos other)
{
return X == other.X && Y == other.Y;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Pos && Equals((Pos) obj);
}
public override int GetHashCode()
{
unchecked
{
return (X*397) ^ Y;
}
}
public static bool operator ==(Pos left, Pos right)
{
return left.Equals(right);
}
public static bool operator !=(Pos left, Pos right)
{
return !left.Equals(right);
}
}
注意,如果你使用c# -6,你可以从属性声明中删除private set