C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The object.ReferenceEquals method gives you the ability to determine if 2 objects are in the same memory location.
Call 1: The first call to object.ReferenceEquals returns false because those 2 memory locations are different.
Call 2: The second call returns true because the references were set equal in an assignment.
Info: Assignments in the C# language perform a simple bitwise copy of the value. This makes the reference equivalent.
Calls 3 and 4: The two references literal1 and literal2 are equal. They point to the same memory location. String literals are pooled.
String Literalstring.InternC# program that uses object.ReferenceEquals
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));
}
}
Output
False
True
True
True
Info: ReferenceEquals was fast. It was a faster way of testing two objects for equality than comparing a unique Id field.
Thus: With objects similar to A, object.ReferenceEquals is not slow. We can use it without too much concern.
C# program that tests object.ReferenceEquals
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"));
Console.Read();
}
}
Result when same equals true
0.32 ns [object.ReferenceEquals]
0.64 ns
Result when same equals false
0.64 ns [object.ReferenceEquals]
0.64 ns