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
@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