Skip to content

Instantly share code, notes, and snippets.

@mitio
Last active December 27, 2015 23:19
Show Gist options
  • Save mitio/7404926 to your computer and use it in GitHub Desktop.
Save mitio/7404926 to your computer and use it in GitHub Desktop.
A small benchmark testing the toll of converting a block to a Proc object.
# With Ruby 2.1.0-preview1 this benchmark outputs:
#
# user system total real
# calling_with_param 1.450000 0.150000 1.600000 ( 1.874802)
# calling_with_proc_new 0.920000 0.060000 0.980000 ( 1.004593)
# calling_with_yield 0.220000 0.000000 0.220000 ( 0.233624)
# returning_with_param 1.300000 0.080000 1.380000 ( 1.414610)
# returning_with_proc_new 0.830000 0.040000 0.870000 ( 0.880629)
require 'benchmark'
def calling_with_param(needs_proc_object, &blk)
if needs_proc_object
blk.call
else
yield
end
end
def calling_with_proc_new(needs_proc_object)
if needs_proc_object
Proc.new.call
else
yield
end
end
def calling_with_yield(needs_proc_object)
yield
end
def returning_with_param(needs_proc_object, &blk)
blk if needs_proc_object
end
def returning_with_proc_new(needs_proc_object)
Proc.new if needs_proc_object
end
runs = 1_000_000
Benchmark.bm do |bm|
bm.report('calling_with_param ') { runs.times { |run| calling_with_param(run.even?) {} } }
bm.report('calling_with_proc_new ') { runs.times { |run| calling_with_proc_new(run.even?) {} } }
bm.report('calling_with_yield ') { runs.times { |run| calling_with_yield(run.even?) {} } }
bm.report('returning_with_param ') { runs.times { |run| returning_with_param(run.even?) {} } }
bm.report('returning_with_proc_new') { runs.times { |run| returning_with_proc_new(run.even?) {} } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment