Last active
August 29, 2018 17:47
-
-
Save joshsusser/e8cc7980f54957b382af60e28f7534ed to your computer and use it in GitHub Desktop.
benchmarking && vs try
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
module ActiveSupport | |
module NewTryable #:nodoc: | |
def try(*a, &b) | |
return unless a.empty? || respond_to?(a.first) | |
return public_send(*a, &b) unless a.empty? | |
return nil unless block_given? | |
return instance_eval(&b) if b.arity == 0 | |
yield self | |
end | |
def try!(*a, &b) | |
return public_send(*a, &b) if !a.empty? | |
return nil unless block_given? | |
return instance_eval(&b) if b.arity == 0 | |
yield self | |
end | |
end | |
end | |
module ActiveSupport | |
module OldTryable #:nodoc: | |
def try(*a, &b) | |
try!(*a, &b) if a.empty? || respond_to?(a.first) | |
end | |
def try!(*a, &b) | |
if a.empty? && block_given? | |
if b.arity == 0 | |
instance_eval(&b) | |
else | |
yield self | |
end | |
else | |
public_send(*a, &b) | |
end | |
end | |
end | |
end | |
class FooNew | |
include ActiveSupport::NewTryable | |
def foo | |
end | |
end | |
class FooOld | |
include ActiveSupport::OldTryable | |
def foo | |
end | |
end | |
class Foo | |
def foo | |
end | |
end | |
foo_and = Foo.new | |
foo_safe = Foo.new | |
foo_new = FooNew.new | |
foo_old = FooOld.new | |
require 'benchmark/ips' | |
Benchmark.ips do |x| | |
x.report("and") { foo_and && foo_and.foo } | |
x.report("safe") { foo_safe&.foo } | |
x.report("old") { foo_old.try(:foo) } | |
x.report("new") { foo_new.try(:foo) } | |
x.compare! | |
end | |
# $ ruby try-bench.rb | |
# Warming up -------------------------------------- | |
# and 318.461k i/100ms | |
# safe 319.158k i/100ms | |
# old 148.504k i/100ms | |
# new 180.076k i/100ms | |
# Calculating ------------------------------------- | |
# and 10.309M (± 1.9%) i/s - 51.591M in 5.006308s | |
# safe 10.947M (± 2.0%) i/s - 54.895M in 5.016615s | |
# old 2.298M (± 1.1%) i/s - 11.583M in 5.040476s | |
# new 3.127M (± 1.4%) i/s - 15.667M in 5.010648s | |
# | |
# Comparison: | |
# safe: 10947229.7 i/s | |
# and: 10309178.2 i/s - 1.06x slower | |
# new: 3127291.1 i/s - 3.50x slower | |
# old: 2298362.3 i/s - 4.76x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment