Last active
January 7, 2021 13:26
-
-
Save aienabled/3cf2d43052a113aae16dfe4021493068 to your computer and use it in GitHub Desktop.
A C# console program to microbenchmark equality methods. It confirms that there is NO performance difference with `ReferenceEquals` and `==` operator for reference type (class).
This file contains hidden or 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; | |
public class EqualityBenchmark | |
{ | |
private const int NumberOfComparisons = 100000; | |
[Benchmark] | |
public string EqualityWithOperator() | |
{ | |
var a = new Foo(); | |
var b = new Foo(); | |
var counter = 0; | |
for (int i = 0; i < NumberOfComparisons; i++) | |
{ | |
if (a == b) | |
{ | |
counter++; | |
} | |
} | |
return counter.ToString(); | |
} | |
[Benchmark] | |
public string EqualityWithReferenceEquals() | |
{ | |
var a = new Foo(); | |
var b = new Foo(); | |
var counter = 0; | |
for (int i = 0; i < NumberOfComparisons; i++) | |
{ | |
if (ReferenceEquals(a, b)) | |
{ | |
counter++; | |
} | |
} | |
return counter.ToString(); | |
} | |
internal class Foo | |
{ | |
} | |
} |
This file contains hidden or 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.Running; | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<EqualityBenchmark>(); | |
} | |
} |
This file contains hidden or 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
| Method | Mean | Error | StdDev | | |
|---------------------------- |---------:|---------:|---------:| | |
| EqualityWithOperator | 46.73 us | 0.023 us | 0.019 us | | |
| EqualityWithReferenceEquals | 46.73 us | 0.007 us | 0.005 us | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment