1

I revisited the ruby koans and I saw something like

 # THINK ABOUT IT:¬                                                                              
 30     #¬                                                                                              
 31     # Is it better to use¬                                                                          
 32     #    obj.nil?¬                                                                                  
 33     # or¬                                                                                           
 34     #    obj == nil¬                                                                                
 35     # Why?

What really is better?

I am on the side of obj.nil since it is easier to read and shorter. But is there a solid proof on which is better?

Norly Canarias
  • 1,736
  • 1
  • 21
  • 19

2 Answers2

3

obj.nil? is more readable and more efficient

require 'benchmark'

n = 500000
Benchmark.bm do |x|
  x.report { n.times do ; 1.nil?;   end }
  x.report { n.times do ; 1 == nil; end }
end

#     user     system      total        real
# 0.050000   0.000000   0.050000 (  0.056285)
# 0.100000   0.000000   0.100000 (  0.094164)
Thomas
  • 1,613
  • 8
  • 8
  • 3
    Huh? `obj.nil?` is one variable dereference (`obj`) and one message send (`nil?`). `obj == nil` is *two* variable dereferences (`obj` and `nil`) and one message send (`==`). How is that "more efficient" and how is that "avoiding one function call"? – Jörg W Mittag Oct 31 '14 at 15:10
  • My mistake ! I've corrected the answer – Thomas Oct 31 '14 at 15:15
  • but isn't == a method? just syntactically sweet – Norly Canarias Oct 31 '14 at 15:16
  • `Object#nil?` is better as it represents unambiguous way to check if receiver is `nil`. The comparison operator method `==` does work as a side effect `NilClass` can't be instantiated. If it could and inherited `Object#==` was used, the result would be `false` because two different instances. – David Unric Oct 31 '14 at 17:16
  • Btw. benchmarking here is about implementation detail and won't be surprised by different results between CRuby, JRuby or Opal.So it does not make much sense. – David Unric Oct 31 '14 at 17:21
  • If you write `x.report "nil?" { n.times do ; 1.nil?; end }`, that row in the output will be labelled `nil?`. – Cary Swoveland Oct 31 '14 at 18:25
1

obj.nil? is also more amenable to modification. You could override it without fooling with the more general == method. A could could be using the Null Object Pattern where users also testing for nil directly with nil?.

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80