Skip to content

Instantly share code, notes, and snippets.

@rafbm
Created February 13, 2013 13:37
Show Gist options
  • Save rafbm/4944651 to your computer and use it in GitHub Desktop.
Save rafbm/4944651 to your computer and use it in GitHub Desktop.
Benchmarking `respond_to?` and `rescue NoMethodError` for method delegation in Ruby.
require 'benchmark'
# Say you have a Foo class and you want instances of this class to delegate unknown
# methods to two objects, first to @object_1, then to @object_2.
class Foo
def initialize
@object_1 = nil
@object_2 = ''
end
end
@foo = Foo.new
# Which is faster, first calling respond_to? on @object_1, or calling the method
# directly, then rescue NoMethodError before calling it on @object_2?
Benchmark.benchmark Benchmark::CAPTION, 11 do |bm|
bm.report 'respond_to?' do
class Foo
def method_missing(*args, &block)
(@object_1.respond_to?(args[0]) ? @object_1 : @object_2).send(*args, &block)
end
end
1_000_000.times { @foo.split }
end
bm.report 'rescue' do
class Foo
def method_missing(*args, &block)
@object_1.send(*args, &block)
rescue NoMethodError
@object_2.send(*args, &block)
end
end
1_000_000.times { @foo.split }
end
end
__END__
Results:
user system total real
respond_to? 0.870000 0.000000 0.870000 ( 0.873963)
rescue 13.190000 0.590000 13.780000 ( 13.779372)
respond_to? FTW!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment