Created
July 18, 2011 14:34
-
-
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.
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 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 |
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
$ 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