Last active
August 29, 2015 14:13
-
-
Save scottjacobsen/16b6917c5d74c0ddd52e to your computer and use it in GitHub Desktop.
benchmark_method_missing
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 ViewContext | |
def hello | |
"hello" | |
end | |
end | |
class SimpleMethodMissing | |
def initialize | |
@view_context = ViewContext.new | |
end | |
def foo | |
"bar" | |
end | |
def method_missing(method, *args, &block) | |
@view_context.send method, *args, &block | |
end | |
end | |
class FancyMethodMissing | |
def initialize | |
@view_context = ViewContext.new | |
end | |
def method_missing(method, *args, &block) | |
self.class.define_proxy method | |
send method, *args, &block | |
end | |
def self.define_proxy(name) | |
define_method name do |*args, &block| | |
@view_context.send(name, *args, &block) | |
end | |
end | |
end | |
def test(runs = 1_000_000) | |
Benchmark.bm(8) do |x| | |
x.report('direct:') { for i in 1..runs; SimpleMethodMissing.new.foo {}; end } | |
x.report('simple:') { for i in 1..runs; SimpleMethodMissing.new.hello {}; end } | |
x.report('fancy:') { for i in 1..runs; FancyMethodMissing.new.hello {}; end } | |
end | |
end | |
test | |
### Results 2.1.5 | |
# user system total real | |
# direct: 0.480000 0.000000 0.480000 ( 0.481921) | |
# simple: 1.560000 0.010000 1.570000 ( 1.566712) | |
# fancy: 1.650000 0.000000 1.650000 ( 1.655674) | |
### Results 1.9.3 | |
# user system total real | |
# direct: 1.020000 0.000000 1.020000 ( 1.022496) | |
# simple: 2.860000 0.020000 2.880000 ( 2.880711) | |
# fancy: 2.950000 0.020000 2.970000 ( 2.972795) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment