-
-
Save chancancode/02738ef24afec3a2eb5d to your computer and use it in GitHub Desktop.
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
class Object | |
def try(*a, &b) | |
if a.empty? && block_given? | |
if b.arity.zero? | |
instance_eval(&b) | |
else | |
yield self | |
end | |
else | |
public_send(*a, &b) if respond_to?(a.first) | |
end | |
end | |
def try_delegated!(*a, &b) | |
if a.empty? && block_given? | |
try(*a, &b) | |
else | |
public_send(*a, &b) | |
end | |
end | |
def try_duplicated!(*a, &b) | |
if a.empty? && block_given? | |
if b.arity.zero? | |
instance_eval(&b) | |
else | |
yield self | |
end | |
else | |
public_send(*a, &b) | |
end | |
end | |
end | |
class NilClass | |
def try(*args) | |
nil | |
end | |
def try_delegated!(*args) | |
nil | |
end | |
def try_duplicated!(*args) | |
nil | |
end | |
end | |
require 'benchmark/ips' | |
NIL = nil | |
NOT_NIL = '' | |
Benchmark.ips do |x| | |
x.report('delegated nil without block') { NIL.try_delegated!(:length) } | |
x.report('duplicated nil without block') { NIL.try_duplicated!(:length) } | |
x.report('delegated nil with instance_evaled block') { NIL.try_delegated! { length } } | |
x.report('duplicated nil with instance_evaled block') { NIL.try_duplicated! { length } } | |
x.report('delegated nil with yielded block') { NIL.try_delegated! { |s| s.length } } | |
x.report('duplicated nil with yielded block') { NIL.try_duplicated! { |s| s.length } } | |
x.report('delegated not nil without block') { NOT_NIL.try_delegated!(:length) } | |
x.report('duplicated not nil without block') { NOT_NIL.try_duplicated!(:length) } | |
x.report('delegated not nil with instance_evaled block') { NOT_NIL.try_delegated! { length } } | |
x.report('duplicated not nil with instance_evaled block') { NOT_NIL.try_duplicated! { length } } | |
x.report('delegated not nil with yielded block') { NOT_NIL.try_delegated! { |s| s.length } } | |
x.report('duplicated not nil with yielded block') { NOT_NIL.try_duplicated! { |s| s.length } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: