Skip to content

Instantly share code, notes, and snippets.

@aienabled
Last active January 7, 2021 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aienabled/3cf2d43052a113aae16dfe4021493068 to your computer and use it in GitHub Desktop.
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).
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
{
}
}
using BenchmarkDotNet.Running;
internal class Program
{
private static void Main(string[] args)
{
BenchmarkRunner.Run<EqualityBenchmark>();
}
}
| 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