Created
April 14, 2011 13:01
-
-
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
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 '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