|
using BenchmarkDotNet.Attributes; |
|
using BenchmarkDotNet.Running; |
|
using System; |
|
using System.Collections.Generic; |
|
using System.Diagnostics.CodeAnalysis; |
|
|
|
namespace ConsoleApp59 |
|
{ |
|
class Program |
|
{ |
|
static void Main(string[] args) |
|
{ |
|
BenchmarkRunner.Run<Tests>(); |
|
} |
|
} |
|
|
|
[MemoryDiagnoser] |
|
public class Tests |
|
{ |
|
static readonly HashSet<Poco> _pocos = new HashSet<Poco>(); |
|
|
|
static readonly HashSet<PocoWithEquatable> _pocoWithEquatables = new HashSet<PocoWithEquatable>(); |
|
[GlobalSetup] |
|
public static void PocoSetup() |
|
{ |
|
_pocos.Clear(); |
|
for (var i = 0; i < 100; i++) |
|
{ |
|
for (var j = 0; j < 100; j++) |
|
{ |
|
_pocos.Add(new Poco |
|
{ |
|
A1 = i.ToString(), |
|
A2 = j.ToString(), |
|
I1 = i, |
|
I2 = j |
|
}); |
|
} |
|
} |
|
_pocoWithEquatables.Clear(); |
|
for (var i = 0; i < 100; i++) |
|
{ |
|
for (var j = 0; j < 100; j++) |
|
{ |
|
_pocoWithEquatables.Add(new PocoWithEquatable |
|
{ |
|
A1 = i.ToString(), |
|
A2 = j.ToString(), |
|
I1 = i, |
|
I2 = j |
|
}); |
|
} |
|
} |
|
} |
|
[Benchmark(Baseline = true)] |
|
public bool PocoContains() |
|
{ |
|
var item = new Poco |
|
{ |
|
A1 = "5", |
|
A2 = "50", |
|
I1 = 5, |
|
I2 = 50 |
|
}; |
|
return _pocos.Contains(item); |
|
} |
|
struct Poco |
|
{ |
|
public string A1 { get; set; } |
|
public string A2 { get; set; } |
|
public int I1 { get; set; } |
|
public int I2 { get; set; } |
|
} |
|
|
|
[Benchmark] |
|
public bool PocoWithEquatableContains() |
|
{ |
|
var item = new PocoWithEquatable |
|
{ |
|
A1 = "5", |
|
A2 = "50", |
|
I1 = 5, |
|
I2 = 50 |
|
}; |
|
return _pocoWithEquatables.Contains(item); |
|
} |
|
struct PocoWithEquatable : IEquatable<PocoWithEquatable> |
|
{ |
|
public string A1 { get; set; } |
|
public string A2 { get; set; } |
|
public int I1 { get; set; } |
|
public int I2 { get; set; } |
|
|
|
public override bool Equals(object obj) => |
|
obj is PocoWithEquatable other && Equals(other); |
|
|
|
public bool Equals(PocoWithEquatable other) |
|
{ |
|
return (A1?.Equals(other.A1) ?? false) && |
|
(A2?.Equals(other.A2) ?? false) && |
|
I1.Equals(other.I1) && |
|
I2.Equals(other.I2); |
|
} |
|
|
|
public override int GetHashCode() |
|
{ |
|
unchecked |
|
{ |
|
int hash = 17; |
|
hash = hash * 23 + (A1 ?? "").GetHashCode(); |
|
hash = hash * 23 + (A2 ?? "").GetHashCode(); |
|
hash = hash * 23 + I1.GetHashCode(); |
|
hash = hash * 23 + I2.GetHashCode(); |
|
return hash; |
|
} |
|
} |
|
} |
|
|
|
} |
|
} |