Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created February 23, 2023 02:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postmodern/66dfb41c8cc98f3bc3c2fd2fe7385542 to your computer and use it in GitHub Desktop.
Save postmodern/66dfb41c8cc98f3bc3c2fd2fe7385542 to your computer and use it in GitHub Desktop.
Micro-benchmark for `value != nil` vs. `!value.nil?`
#!/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
@bugloper
Copy link

bugloper commented Mar 3, 2023

@AndrewJGregory Faster due to it bit flipping?

@TruesSpeak
Copy link

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)

@andreavocado
Copy link

This should be a rubocop cop, shouldn't it?

@postmodern
Copy link
Author

@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