【发布时间】:2015-11-29 07:00:37
【问题描述】:
我有以下职位类别:
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 的不同实例。
【问题讨论】:
-
不要将
ToString用作字典键。改为实现IEquatable<Pos>。 -
不需要
ToString()串联。只需使用x + "," + y -
使用
(long) ((x << 32) | y)作为字典键怎么样?我想它会快得多。 -
@Yahya 慢 100 倍并不意味着更快。 string.format 执行您可以手动执行的相同连接工作。此外,它还必须进行格式字符串处理。它不会以任何方式剥夺工作。它增加了。
-
@X-TECH 最终还是会调用
ToString。
标签: c# performance dictionary hash tostring