Is “ReferenceEquals(myObject, null)” better practi

2020-05-29 13:22发布

I have a co-worker who's a fan of writing his null checks as follows:

if (!ReferenceEquals(myObject, null))

I, on the other hand, find this syntax cumbersome to read and prefer:

if (myObject != null)

I've found some articles and stack overflow questions discussing the merits of ReferenceEquals with respect to operator overloading, but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?

标签: c# .net vb.net
9条回答
Bombasti
2楼-- · 2020-05-29 13:47

In terms of null checks, the two should always return the same results. If a non-null reference ever equals null (even when using the Null Object pattern), regardless of whether ReferenceEquals or the == operator was used, it's a very bad thing. So, in that scenario I would use ==/!=.

I would say that, if the == operator were overloaded, using ReferenceEquals might be slightly faster. The first thing an overloaded == should do is see if the two variables point to the same object, so in the case of an overloaded operator you end up with an extra frame on the call stack. Using ReferenceEquals also guarantees that that's the only check performed.

I would generally also use ==/!= in pretty much any other scenario. The entire idea is that the operator defines "equality"; that is not always referential (in fact, most compound objects should be compared structurally for equality; they're equal if their members are equal). The object, theoretically, knows how best to compare itself to another object, for equality, relative order, etc. and so rather than hardcoding a very specific and possibly incorrect piece of logic, you should use the object-oriented nature of the language to let the object tell you whether it's equal to anything else or not.

查看更多
可以哭但决不认输i
3楼-- · 2020-05-29 13:49

The VB.NET tag probably shouldn't have been included in this question as it is not otherwise mentioned, but, for completeness, Is is equivalent to Object.ReferenceEquals and so can always be used instead of that call.

查看更多
霸刀☆藐视天下
4楼-- · 2020-05-29 13:52

ReferenceEquals might be slightly faster. As mentioned before it makes sure that no overloaded Equals operator is being called. Also ReferenceEquals ensures only one comparison is performed instead of possibly 2 depending on the implementation of the overloaded Equals operator. Although it's very likely that the overloaded operator is using ReferenceEquals itself as the first statement.

I personally do use ReferenceEquals, but only on places where I am really tweaking to squeeze out the last clock cycles (places that are possibly called millions of times per second). Or when I have no control over the type, like in the case of generics. ... But again only when performance is really critical.

查看更多
登录 后发表回答