Int32.ToString()太慢了

时间:2015-09-03 12:30:36

标签: c# performance dictionary hash tostring

我有以下职位类别:

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.xPos.y获得单个唯一值的有效方法,用作字典键。 注意:我无法使用Pos,因为我只是在Posx上比较y的不同实例。

1 个答案:

答案 0 :(得分:29)

  

我所需要的只是一种基于的单一唯一值的有效方法   Pos.x和Pos.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