Skip to content

Instantly share code, notes, and snippets.

@scottjacobsen
Last active Aug 29, 2015
Embed
What would you like to do?
benchmark_method_missing
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