Created
February 10, 2010 18:25
-
-
Save flavorjones/300668 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
#! /usr/bin/env ruby | |
require 'benchmark' | |
N = 100_000 | |
puts "Pessimistic:" | |
Benchmark.bm(50) do |bm| | |
array = [] | |
1.upto(N) do | |
array << Object.new | |
end | |
bm.report "respond_to?" do | |
array.each do |object| | |
if object.respond_to?(:xyzzy) | |
raise "should not be here" | |
end | |
end | |
end | |
bm.report "NoMethodError" do | |
array.each do |object| | |
begin | |
object.xyzzy() | |
raise "should not be here" | |
rescue NoMethodError | |
# do nothing | |
end | |
end | |
end | |
end | |
puts "Optimistic:" | |
Benchmark.bm(50) do |bm| | |
array = [] | |
1.upto(N) do | |
array << Object.new | |
end | |
bm.report "respond_to?" do | |
array.each do |object| | |
if object.respond_to?(:inspect) | |
object.inspect | |
else | |
raise "should not be here" | |
end | |
end | |
end | |
bm.report "NoMethodError" do | |
array.each do |object| | |
begin | |
object.inspect | |
rescue NoMethodError | |
raise "should not be here" | |
end | |
end | |
end | |
end | |
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
Pessimistic: | |
user system total real | |
respond_to? 0.080000 0.030000 0.110000 ( 0.116358) | |
NoMethodError 1.110000 0.090000 1.200000 ( 1.216291) | |
Optimistic: | |
user system total real | |
respond_to? 0.140000 0.050000 0.190000 ( 0.198011) | |
NoMethodError 0.160000 0.050000 0.210000 ( 0.211779) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment