So I thought I was being clever, writing my Rails controller actions like this:
def create
set_post_from_post_id
set_comment_as_new
respond_to do |format|
comment.save
format.js(&method(:create_respond_to_js))
format.html(&method(:create_respond_to_html))
end
end
The individual mime type handlers are written as private methods and passed in as proc objects by essentially calling to_proc
on the instance method objects.
I was curious to see just how much faster my new, elegant, and super-clever solution was.
Benchmarking revealed that it's not.
Don't do it.
require 'benchmark'
TIMES = 100000
module MyThing
module_function
def handle_proc(&block)
block.call
end
def my_method
("madness" * 10) + Time.now.to_s
end
end
Benchmark.bmbm do |test|
test.report("With method()") do
TIMES.times { MyThing.handle_proc(&MyThing.method(:my_method)) }
end
test.report("Calling method from block") do
TIMES.times { MyThing.handle_proc { MyThing.my_method } }
end
end
Rehearsal -------------------------------------------------------------
With method() 0.870000 0.000000 0.870000 ( 0.890830)
Calling method from block 0.710000 0.010000 0.720000 ( 0.723961)
---------------------------------------------------- total: 1.590000sec
user system total real
With method() 0.860000 0.010000 0.870000 ( 0.892515)
Calling method from block 0.650000 0.000000 0.650000 ( 0.678533)