public
Last active — forked from zeroed/respond_to_vs_include.rb

Modified version which compares the single method check times (which need to include Mock.instance_methods(false)).

  • Download Gist
respond_to_vs_include.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
# Fancy benchmark...
# is respond_to? so faster than include?
 
require 'benchmark'
 
n = 10_000_000
mock_methods = ('a'..'z').to_a
 
class Mock
end
 
mock_methods.each do |m|
Mock.class_eval do
send(:attr_accessor, m)
end
end
 
mock = Mock.new
instance_meths = Mock.instance_methods(false)
 
Benchmark.bm(15) do |test|
test.report('respond_to?: ') do
n.times do
mock.respond_to? :k
end
end
test.report('include?: ') do
n.times do
instance_meths.include? :k
end
end
test.report('instance_methods.include?: ') do
n.times do
Mock.instance_methods(false).include? :k
end
end
end
times.txt
1 2 3 4 5
$ ruby respond_to_vs_include-RK.rb
user system total real
respond_to?: 1.170000 0.000000 1.170000 ( 1.167067)
include?: 7.862000 0.000000 7.862000 ( 7.880450)
instance_methods.include?: 152.242000 0.000000 152.242000 (152.295711)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.