Skip to content

Instantly share code, notes, and snippets.

@jonleighton
Created July 18, 2011 14:34
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 jonleighton/1089684 to your computer and use it in GitHub Desktop.
Save jonleighton/1089684 to your computer and use it in GitHub Desktop.
A benchmark of the speed of two options for backporting Ruby 1.9's public_send method to 1.8.7. The first one wins by far.
require 'benchmark'
class Object
def public_send_public_method_defined(method, *args, &block)
singleton_class = (class << self; self; end)
if singleton_class.public_method_defined?(method)
send(method, *args, &block)
else
raise # this doesn't matter, as it's not the path we're benchmarking
end
end
def public_send_methods(method, *args, &block)
if methods.include?(method.to_s)
send(method, *args, &block)
else
raise # this doesn't matter, as it's not the path we're benchmarking
end
end
end
class Foo
def bar
end
end
n = 100_000
Benchmark.bmbm(20) do |b|
b.report('public_method_defined?') do
n.times { Foo.new.public_send_public_method_defined(:bar) }
end
b.report('methods') do
n.times { Foo.new.public_send_methods(:bar) }
end
end
$ ruby public_send_benchmark.rb
Rehearsal ----------------------------------------------------------
public_method_defined? 0.530000 0.000000 0.530000 ( 0.533415)
methods 2.820000 0.000000 2.820000 ( 2.833929)
------------------------------------------------- total: 3.350000sec
user system total real
public_method_defined? 0.530000 0.000000 0.530000 ( 0.529561)
methods 3.140000 0.000000 3.140000 ( 3.155589)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment