Is there extra overhead in using the object.ReferenceEquals
method verses using ((object)obj1 == (object)obj2)
?
In the first case, there would be a static method call involved, and in both cases some form of casting to an object would be involved.
Even if the compiler balances out those methods, what about inequality?
(object)obj != null
as compared to...
!object.ReferenceEquals(obj,null)
I suppose that at some point, a logical negation would occur, either within the != operator, or as applied to the result of the ReferenceEquals method. What do you think?
There's also the issue of readability to consider. ReferenceEquals seems clearer when checking equality, but for inequality, one might miss the !
preceding object.ReferenceEquals
, whereas the !=
in the first variation is hard to overlook.
Is there extra overhead in using the object.ReferenceEquals method
No. The method directly contains the minimal IL description to perform the reference equality check (for the record: it's equivalent to VB's Is
operator) and will often be inlined by the JIT (especially when targeting x64) so there's no overhead.
About readability: I personally think that object.ReferenceEquals
is potentially more readable (even in the negated form) because it explicitly expresses its semantics. The cast to object
may be confusing to some programmers.
I've just found an article discussing this. It prefers (object)x == y
because the IL footprint is smaller. It argues that this might facilitate inlining of method X
using this comparison. However (without any detailed knowledge of the JIT but logically and intuitively) I believe this is wrong: if the JIT behaves anything like an optimizing C++ compiler, it will consider the method after inlining the call to ReferenceEquals
, so (for the sake of inlining method X
) the memory footprint will be exactly the same either way.
That is to say: choosing one way over the other will have no impact whatsoever on the JIT and consequently on performance.