Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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