Created
February 11, 2020 01:42
-
-
Save meziantou/605934eb7376d9c3cc46af0adad937e6 to your computer and use it in GitHub Desktop.
Struct - HashSet benchmark
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
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