Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Struct - HashSet benchmark
public class Hashset
{
[Benchmark]
public void HashSet_Int32()
{
var hashset = new HashSet<int>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(i);
}
}
[Benchmark]
public void HashSet_Struct()
{
var hashset = new HashSet<Struct>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(new Struct(i));
}
}
[Benchmark]
public void HashSet_StructWithReferenceType()
{
var hashset = new HashSet<StructWithReferenceType>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(new StructWithReferenceType(null));
}
}
[Benchmark]
public void HashSet_StructWithOverrides()
{
var hashset = new HashSet<StructWithOverrides>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(new StructWithOverrides(i));
}
}
[Benchmark]
public void ReadOnlyStruct()
{
var hashset = new HashSet<ReadOnlyStruct>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(new ReadOnlyStruct(i));
}
}
[Benchmark]
public void ReadOnlyStructWithOverrides()
{
var hashset = new HashSet<ReadOnlyStructWithOverrides>();
for (int i = 0; i < 1000; i++)
{
hashset.Add(new ReadOnlyStructWithOverrides(i));
}
}
[Benchmark]
public void HashSet_Enum()
{
var hashset = new HashSet<Enum>();
for (int i = 0; i < 1000; i++)
{
hashset.Add((Enum)i);
}
}
}
internal enum Enum
{
}
internal struct StructWithReferenceType
{
public object Value;
public StructWithReferenceType(object value)
{
Value = value;
}
}
internal struct Struct
{
public int Value;
public Struct(int value)
{
Value = value;
}
}
internal readonly struct ReadOnlyStruct
{
public readonly int Value;
public ReadOnlyStruct(int value)
{
Value = value;
}
}
internal readonly struct ReadOnlyStructWithOverrides
{
public readonly int Value;
public ReadOnlyStructWithOverrides(int value)
{
Value = value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override bool Equals(object obj)
{
return obj is StructWithOverrides s && s.Value.Equals(Value);
}
}
public static class Program
{
public static void Main()
{
BenchmarkRunner.Run<Hashset>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.