Created
September 9, 2023 10:19
-
-
Save ismkdc/0d6a3e562a0b0bad7308f2383efb04e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
namespace HashSetDemo; | |
public class Benchmarks | |
{ | |
private static readonly HashSet<foo1> hashset1 = new HashSet<foo1>(); | |
private static readonly HashSet<foo2> hashset2 = new HashSet<foo2>(); | |
[GlobalSetup] | |
public void Setup() | |
{ | |
for (int i = 0; i <= 10_000; i++) | |
{ | |
hashset1.Add(new foo1 | |
{ | |
Id = i, | |
Name = Guid.NewGuid().ToString() | |
}); | |
hashset2.Add(new foo2 | |
{ | |
Id = i, | |
Name = Guid.NewGuid().ToString() | |
}); | |
} | |
} | |
[Benchmark] | |
public void HashSetTest1() | |
{ | |
var foo = new foo1 | |
{ | |
Id = 1, | |
}; | |
for (int i = 0; i < 1_000; i++) | |
{ | |
_ = hashset1.Contains(foo); | |
} | |
} | |
[Benchmark] | |
public void HashSetTest2() | |
{ | |
for (int i = 0; i < 1_000; i++) | |
{ | |
_ = hashset2.Any(h => h.Id == i); | |
} | |
} | |
} | |
public class foo1 | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public override int GetHashCode() | |
{ | |
return Id; | |
} | |
public override bool Equals(object obj) | |
{ | |
if (obj is foo1 otherFoo) | |
{ | |
return Id == otherFoo.Id; | |
} | |
return false; | |
} | |
} | |
public class foo2 | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment