Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.ToString() too slow

I have the following for a position 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();
    }
}

But since I am calling Pos.ToString() thousands of times, this is too slow for me. 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. Note: I cannot use Pos because I am comparing different instances of Pos on merely x and y.

like image 444
TheAbelo2 Avatar asked Sep 03 '15 12:09

TheAbelo2


1 Answers

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.

Don't use ToString as a way to generate unique dictionary keys, implement IEquatable<Pos> instead. This way, you don't have to allocate any strings at all to measure equality:

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);
    }
}

Note you can remove the private set from the properties declarations if you're using C#-6.

like image 192
Yuval Itzchakov Avatar answered Oct 11 '22 16:10

Yuval Itzchakov