Is it better to use obj.nil?
or obj == nil
and what are the benefits of both?
The actual results showed that using obj as a nil check is the fastest in all cases. obj is consistently faster by 30% or more than checking obj. nil? . Surprisingly, obj performs about 3-4 times as fast as variations on obj == nil , for which there seems to be a punishing performance penalty.
Nil means nothing/nonexistent. Ask Matz. It's not different. Just a guess: Ruby is very lisp-like and nil is a value in lisp.
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.
nil is an Object, NULL is a memory pointer Sadly, when this happens, Ruby developers are confusing a simple little Ruby object for something that's usually radically different in “blub” language. Often, this other thing is a memory pointer, sometimes called NULL, which traditionally has the value 0.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With