开发者

Best and fastest way to check if an object is null [duplicate]

开发者 https://www.devze.com 2023-01-30 02:39 出处:网络
This question already has answers here: Reference equality performance difference? ((object)obj1 == (object)obj2) vs. object.ReferenceEquals( obj1, obj2 )
This question already has answers here: Reference equality performance difference? ((object)obj1 == (object)obj2) vs. object.ReferenceEquals( obj1, obj2 ) (6 answers) Closed 9 years ago. 开发者_如何转开发

I often see in source codes the usage of if (object.ReferenceEquals(myObject, null)) for checking if myObject is null instead of if (myObject == null) which I am familiar with.

Is there any particular reason (like speed, readability, etc) for using the first way instead of the second one? Which one do you use?

Thank you in advance.


When using ReferenceEquals you make sure that no special handling (overloaded operator for instance) is being applied. This also leads to different results if used with unbound generics.


Simple things are usually the most efficient : (myObject == null) is more performant

Look at this article


Take a look at this interesting article

Performance Tip: Prefer (((Object) x)== null) to Object.ReferenceEquals(x,null)


The == operator can be overloaded by class implementations, so it might not do a reference comparision (though it probably should with nulls). object.ReferenceEquals can't, so it reliably always does a reference comparision.

Cheers Matthias


The ReferenceEquals method cannot be overridden and so you can always be certain that the comparison is going to compare the object references and not be passed to some override of the Equals method.


They usually have the same effect, although they compile to different things. if (myObject == null) results in a ceq opcode, which I'd expect to compile to quicker code. object.ReferenceEquals is a method call like any other.

They're different when myObject has an operator= method; when this is present, your code calls into this method instead of using ceq. operator= can then do whatever it likes.

Always if (myObject == null) unless you have a reason not to.

0

精彩评论

暂无评论...
验证码 换一张
取 消