Just stumbled over this question on Stackoverflow.com.
What is the difference between nil? and == nil?.
There is no difference.
At least when looking at the observable outcome. And I prefer nil? because of readability. But that is just a matter of taste.
However there is a slight difference in how this outcome is calculated.
nil?
nil? is a method defined on Object and NilClass.
Unless you mess with this implementation through monkeypatching a nil? check is a simple method call.
For your own objects (unless they inherit from BasicObject which does not implement nil?) the implementation stems from
Object and will always return false.
== nil
a == b is just syntactic sugar for sending the == message to the left hand side, passing the right hand side as sole argument. This translates to
a.==(b) in the general case. And to a.==(nil) in our specific case.
At the Object level, == returns true only if obj and other are the same object.
So this returns true if two variables are pointing to the same object or if the receiving class has overridden the == method in another way. And subclasses are meant to override == to implement class specific behavior.
This also means that the performance depends on the implementation of ==. Unlike nil? which should not be overridden by subclasses.
Another solution
In ruby everything besides nil and false is considered truthy. If this interpretation fits your use case, then you can avoid the check and pass the object to the if clause directly:
Performance
I’d expect nil? to be as fast as == nil. And because == might be overridden by subclasses performance should depend upon the receiver.
And omitting the check should be fastest.
Here is a simple benchmark to test my assumptions. As usual, I use the wonderful benchmark/ips gem by Evan Phoenix.
I did not expect nil? to be slower, still looking into this. But one can see that if you go for the == check, then it should be faster if you do nil == other instead of other == nil. Usual micro benchmark warnings apply.