Micro-benchmark for `value != nil` vs. `!value.nil?`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'benchmark' | |
Benchmark.bm do |b| | |
n = 1_000_000 | |
value1 = 1 | |
value2 = nil | |
b.report('value != nil') do | |
n.times do | |
value1 != nil | |
value2 != nil | |
end | |
end | |
b.report('!value.nil?') do | |
n.times do | |
!value1.nil? | |
!value2.nil? | |
end | |
end | |
end |
and if we also test nil != value
, it's only slightly slower:
user system total real
value != nil 0.332498 0.000000 0.332498 ( 0.334777)
nil != vaule 0.072327 0.000000 0.072327 ( 0.072743)
!value.nil? 0.061445 0.000000 0.061445 ( 0.061947)
Why?
@AndrewJGregory Faster due to it bit flipping?
ruby 2.7.6p219:
user system total real
value != nil 0.137024 0.000028 0.137052 ( 0.137107)
!value.nil? 0.031404 0.000000 0.031404 ( 0.031418)
This should be a rubocop cop, shouldn't it?
@andreavocado it actually is! At first I didn't believe it would have improved the code, which is why I wrote the benchmark.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ruby-3.1.1:
ruby-3.2.0 (no JIT):