Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

c# - Reference equality performance difference? ((object)obj1 == (object)obj2) vs. object.ReferenceEquals( obj1, obj2 )

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...