What wizardry is in that System.Drawing.Point class that makes it so much faster than my simple struct?
It's quite a bit faster. I'm getting 1-5ms on Point class and 2000ms or more on my struct.
Looking at the Points.cs source, I'm not skilled enough to spot what is doing it. I made an attempt at implementing IEquatable (probably incorrectly) and couldn't make any gains.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
int elementsInSets = 10000;
int lookupCount = 10000;
// Point struct from System.Drawing
HashSet<Point> myPoints = new HashSet<Point>();
for (int i = 0; i < elementsInSets; i++)
{
myPoints.Add(new Point(i, i));
}
// My simple struct
HashSet<P> myPoints2 = new HashSet<P>();
for (int i = 0; i < elementsInSets; i++)
{
myPoints2.Add(new P(i, i));
}
sw.Start();
for (int j = 0; j < lookupCount; j++)
{
if (myPoints2.Contains(new P(j, j)))
{
//found
}
}
Console.WriteLine("simple P " + sw.ElapsedMilliseconds + "ms");
sw.Restart();
for (int j = 0; j < lookupCount; j++)
{
if (myPoints.Contains(new Point(j, j)))
{
// found
}
}
Console.WriteLine("Point " + sw.ElapsedMilliseconds + "ms");
}
}
public struct P
{
int x;
int y;
public P(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
}