Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Last active August 29, 2015 14:22
Show Gist options
  • Save Bodacious/03bdeb34cf9cddc0f16b to your computer and use it in GitHub Desktop.
Save Bodacious/03bdeb34cf9cddc0f16b to your computer and use it in GitHub Desktop.
Ruby: Passing Method objects into methods that accept blocks is SLOWER than procs

Explanation

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment