Skip to content

Instantly share code, notes, and snippets.

@schneems
Created October 3, 2018 19:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schneems/3362399f84de6a8a054f6de63a3ac6e1 to your computer and use it in GitHub Desktop.
Save schneems/3362399f84de6a8a054f6de63a3ac6e1 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
nil_case = nil
Benchmark.ips do |x|
x.report("nil &. ") { nil_case&.try(:foo) }
x.report("nil try") { nil_case.try(:foo) }
x.compare!
end
# Warming up --------------------------------------
# nil &. 309.913k i/100ms
# nil try 192.341k i/100ms
# Calculating -------------------------------------
# nil &. 11.042M (± 6.4%) i/s - 55.165M in 5.022975s
# nil try 3.569M (± 7.7%) i/s - 17.888M in 5.043223s
# Comparison:
# nil &. : 11042472.9 i/s
# nil try: 3568893.8 i/s - 3.09x slower
foo_case = Class.new { def foo; "foo" end }.new
Benchmark.ips do |x|
x.report("non-nil &. ") { foo_case&.try(:foo) }
x.report("non-nil try") { foo_case.try(:foo) }
x.compare!
end
# Warming up --------------------------------------
# non-nil &.
# 147.334k i/100ms
# non-nil try 138.635k i/100ms
# Calculating -------------------------------------
# non-nil &. 2.258M (± 4.8%) i/s - 11.345M in 5.036496s
# non-nil try 2.045M (±12.8%) i/s - 10.120M in 5.043652s
# Comparison:
# non-nil &. : 2258024.8 i/s
# non-nil try: 2044922.0 i/s - same-ish: difference falls within error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment