Skip to content

Instantly share code, notes, and snippets.

@joncham
Last active July 25, 2017 22:04
Show Gist options
  • Save joncham/844017faba882d1d1d847bd6b0511e49 to your computer and use it in GitHub Desktop.
Save joncham/844017faba882d1d1d847bd6b0511e49 to your computer and use it in GitHub Desktop.
Delegate GetHashCode Performance
//#define USE_CUSTOM_COMPARER
using System;
using System.Collections.Generic;
using System.Diagnostics;
public class Program
{
private const int Iterations = 8000;
public static void Main (string[] args)
{
var foos = new List<Foo> ();
var set = new HashSet<Action> (
#if USE_CUSTOM_COMPARER
new ActionEqualityComparer ()
#endif
);
for (var i = 0; i < Iterations; i++)
{
foos.Add (new Foo ());
set.Add(foos[i].Bar);
}
var stopwatch = new Stopwatch ();
stopwatch.Start ();
var total = 0;
foreach (var foo in foos)
total += set.Contains (foo.Bar) ? 1 : 0;
stopwatch.Stop ();
Console.WriteLine ("Duration: " + stopwatch.ElapsedMilliseconds + " ms ");
GC.KeepAlive (total);
}
class Foo { public void Bar () { } }
class ActionEqualityComparer : EqualityComparer<Action>
{
public override bool Equals (Action x, Action y)
{
return x.Equals (y);
}
public override int GetHashCode (Action obj)
{
if (obj == null)
return 0;
return obj.Target != null ? obj.Target.GetHashCode () : obj.GetHashCode ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment