obj.nil? vs. obj == nil

Viewed 18831

Is it better to use obj.nil? or obj == nil and what are the benefits of both?

7 Answers

Is it better to use obj.nil? or obj == nil

It is exactly the same. It has the exact same observable effects from the outside ( pfff ) *

and what are the benefits of both.

If you like micro optimizations all the objects will return false to the .nil? message except for the object nil itself, while the object using the == message will perform a tiny micro comparison with the other object to determine if it is the same object.

* See comments.

Personally, I prefer object.nil? as it can be less confusing on longer lines; however, I also usually use object.blank? if I'm working in Rails as that also checks to see if the variable is empty.

I find myself not using .nil? at all when you can do:

unless obj
  // do work
end

It's actually slower using .nil? but not noticeably. .nil? is just a method to check if that object is equal to nil, other than the visual appeal and very little performance it takes there is no difference.

Some might suggest that using .nil? is slower than the simple comparison, which makes sense when you think about it.

But if scale and speed are not your concern, then .nil? is perhaps more readable.

Related