Skip to content

Instantly share code, notes, and snippets.

@stiang
Created April 14, 2011 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stiang/919428 to your computer and use it in GitHub Desktop.
Save stiang/919428 to your computer and use it in GitHub Desktop.
Benchmarks two different ways to call methods that may or may not be defined
require 'benchmark'
class Foo
def bar
1+1
end
end
fmt = '%.2f'
count = 1000000
f = Foo.new
rescue_time = Benchmark.measure do
count.times do
begin
f.send "_bar"
rescue NoMethodError
f.bar
end
end
end
respond_time = Benchmark.measure do
count.times do
unless f.respond_to? "_bar"
f.bar
end
end
end
direct_time = Benchmark.measure { count.times { f.bar } }
puts "Showing results for #{count} method calls"
puts ""
puts "Method IS NOT defined"
puts "====================="
puts "With rescue: #{fmt % rescue_time.real} seconds"
puts "With respond_to: #{fmt % respond_time.real} seconds"
puts "Direct call: #{fmt % direct_time.real} seconds"
rescue_time = Benchmark.measure do
count.times do
f.send "bar"
end
end
respond_time = Benchmark.measure do
count.times do
if f.respond_to? "bar"
f.send "bar"
end
end
end
puts ""
puts "Method IS defined"
puts "================="
puts "With rescue: #{fmt % rescue_time.real} seconds"
puts "With respond_to: #{fmt % respond_time.real} seconds"
puts "Direct call: #{fmt % direct_time.real} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment