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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With