Last active
January 20, 2021 11:34
-
-
Save alchimere/1cd424ee8b093867a88d82026734c78c to your computer and use it in GitHub Desktop.
Bench try vs &.
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bench result on my machine with ruby-2.5.3:
&.
is:.try(:symbol)
when object is nil.try(:symbol)
when object is not nil and more than 12 times faster than.try { ... }