Ruby question - == nil or nil? [duplicate]
Possible Duplicate:
obj.nil? vs. obj ==开发者_如何学JAVA nil
I found a question - which one is better == nil
or nil
?
There is one difference: A class may define nil? as true:
class X
def nil?()
true
end
end
puts X.new.nil? #-> true
Or a practical example (i don't recommend it, if you need it, I would define a nil_or_empty?):
class String
def nil?()
return empty?
end
end
puts 'aa'.nil? #-> false
puts ''.nil? #-> true
Running a benchmark nil? seems to be a bit faster.
require 'benchmark'
TEST_LOOPS = 100_000_000
C_A = nil
C_B = 'aa'
Benchmark.bmbm(10) {|b|
b.report('nil?') {
TEST_LOOPS.times {
x = C_A.nil?
x = C_B.nil?
} #Testloops
}
b.report('==nil') {
TEST_LOOPS.times {
x = ( C_A == nil )
x = ( C_B == nil )
} #Testloops
} #b.report
} #Benchmark
Result:
Rehearsal ---------------------------------------------
nil? 27.454000 0.000000 27.454000 ( 27.531250)
==nil 31.000000 0.000000 31.000000 ( 31.078125)
----------------------------------- total: 58.454000sec
user system total real
nil? 27.515000 0.000000 27.515000 ( 27.546875)
==nil 31.125000 0.000000 31.125000 ( 31.171875)
Although the two operations are very different I'm pretty sure they will always produce the same result. (One calls the #nil?
method of a NilClass object and one compares against the nil
singleton.)
I would suggest that when in doubt you go a third way, actually, and just test the truth value of an expression.
So, if x
and not if x == nil
or if x.nil?
, in order to have this test DTRT when the expression value is false.
精彩评论