Skip to content

Instantly share code, notes, and snippets.

@flavorjones
Created February 10, 2010 18:25
Show Gist options
  • Save flavorjones/300668 to your computer and use it in GitHub Desktop.
Save flavorjones/300668 to your computer and use it in GitHub Desktop.
#! /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
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