Int32.ToString() 太慢了
Int32.ToString() too slow
我有以下职位class:
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
的不同实例
All I need is an efficient way to get a single unique value based on
Pos.x and Pos.y, for use as a dictionary key.
不要使用 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
。
我有以下职位class:
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
的不同实例
All I need is an efficient way to get a single unique value based on Pos.x and Pos.y, for use as a dictionary key.
不要使用 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
。