Object.ReferenceEquals
The C# object.ReferenceEquals
method compares references. When you allocate an object, you receive a reference containing a value indicating its memory location.
The object.ReferenceEquals
method gives you the ability to determine if 2 objects are in the same memory location. The data pointed to is not compared.
Two StringBuilders
are allocated upon the managed heap. The identifiers builder1 and builder2 are reference variables. They contain values that points to those locations on the heap.
object.ReferenceEquals
returns false because those 2 memory locations are different.String
literals are pooled.using System; using System.Text; class Program { static void Main() { // Test object.ReferenceEquals. StringBuilder builder1 = new StringBuilder(); StringBuilder builder2 = new StringBuilder(); Console.WriteLine(object.ReferenceEquals(builder1, builder2)); builder1 = builder2; Console.WriteLine(object.ReferenceEquals(builder1, builder2)); // Test object.ReferenceEquals on string literals. string literal1 = "a"; string literal2 = "a"; Console.WriteLine(object.ReferenceEquals(literal1, literal2)); literal1 = literal2; Console.WriteLine(object.ReferenceEquals(literal1, literal2)); } }False True True True
Is object.ReferenceEquals
a slow or fast method call? I developed this console program that tests the performance of object.ReferenceEquals
on a custom class
.
ReferenceEquals
was fast. It was a faster way of testing two objects for equality than comparing a unique Id field.object.ReferenceEquals
is not slow. We can use it without too much concern.using System; using System.Diagnostics; class A { public int Id; } class Program { const int _max = 1000000000; static void Main() { bool same = true; A a1 = new A() { Id = 1 }; A a2 = same ? a1 : new A() { Id = 2 }; int x = 0; var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { if (object.ReferenceEquals(a1, a2)) { x++; } } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { if (a1.Id == a2.Id) { x++; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }0.32 ns [object.ReferenceEquals] 0.64 ns0.64 ns [object.ReferenceEquals] 0.64 ns
References in the C# language refer to a location in memory. By comparing references with ReferenceEquals
, we determine if 2 variables have an identical location in memory.