Skip to content

Instantly share code, notes, and snippets.

@alchimere
Last active January 20, 2021 11:34
Show Gist options
  • Save alchimere/1cd424ee8b093867a88d82026734c78c to your computer and use it in GitHub Desktop.
Save alchimere/1cd424ee8b093867a88d82026734c78c to your computer and use it in GitHub Desktop.
Bench try vs &.
require 'active_support/all'
require 'benchmark'
# Bench try vs &. on nil case
foo = nil
class Bar
def lala
# does nothing
end
end
# Bench try vs &. on non nil case
bar = Bar.new
N = 10_000_000
Benchmark.bmbm(20) do |x|
x.report('nil.try(:lala)') { N.times { foo.try(:lala) } }
x.report('nil.try { lala }') { N.times { foo.try { lala } } }
x.report('nil&.lala') { N.times { foo&.lala } }
x.report('bar.try(:lala)') { N.times { bar.try(:lala) } }
x.report('bar.try { lala }') { N.times { bar.try { lala } } }
x.report('bar&.lala') { N.times { bar&.lala } }
end
@alchimere
Copy link
Author

Bench result on my machine with ruby-2.5.3:

Rehearsal --------------------------------------------------------
nil.try(:lala)         1.635858   0.000000   1.635858 (  1.636101)
nil.try { lala }       1.157661   0.000000   1.157661 (  1.157768)
nil&.lala              0.502931   0.000000   0.502931 (  0.503034)
bar.try(:lala)         5.585749   0.000000   5.585749 (  5.586231)
bar.try { lala }       8.729292   0.000000   8.729292 (  8.729568)
bar&.lala              0.704501   0.000000   0.704501 (  0.704562)
---------------------------------------------- total: 18.315992sec

                           user     system      total        real
nil.try(:lala)         1.683136   0.000000   1.683136 (  1.683320)
nil.try { lala }       1.212168   0.000000   1.212168 (  1.212295)
nil&.lala              0.538341   0.000000   0.538341 (  0.538362)
bar.try(:lala)         5.693652   0.000000   5.693652 (  5.694107)
bar.try { lala }       8.778483   0.000000   8.778483 (  8.778756)
bar&.lala              0.715212   0.000000   0.715212 (  0.715251)

&. is:

  • more than 3 times faster than .try(:symbol) when object is nil
  • almost 8 times faster than .try(:symbol) when object is not nil and more than 12 times faster than .try { ... }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment