Skip to content

Instantly share code, notes, and snippets.

@dbenhur
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbenhur/922e76a02d010a67f6c6 to your computer and use it in GitHub Desktop.
Save dbenhur/922e76a02d010a67f6c6 to your computer and use it in GitHub Desktop.
Microbenchmark showing the performance penalty of simply specifying a block capture i method arguments
#!/usr/bin/env ruby
require 'benchmark'
N = 10_000_000
def no_capture
end
def block_capture(&_block)
end
Benchmark.bmbm do |b|
b.report('nop') { N.times{ } }
b.report('no capture no block passed') { N.times{ no_capture } }
b.report('block capture no block passed') { N.times{ block_capture } }
b.report('no capture with block passed') { N.times{ no_capture {} } }
b.report('block capture with block passed') { N.times{ block_capture {} } }
end
__END__
$ ./block_capture_penalty.rb
Rehearsal -------------------------------------------------------------------
nop 0.430000 0.000000 0.430000 ( 0.433004)
no capture no block passed 0.690000 0.000000 0.690000 ( 0.696997)
block capture no block passed 0.850000 0.000000 0.850000 ( 0.845417)
no capture with block passed 0.760000 0.010000 0.770000 ( 0.762127)
block capture with block passed 5.230000 0.020000 5.250000 ( 5.268700)
---------------------------------------------------------- total: 7.990000sec
user system total real
nop 0.420000 0.000000 0.420000 ( 0.423946)
no capture no block passed 0.690000 0.000000 0.690000 ( 0.691389)
block capture no block passed 0.820000 0.000000 0.820000 ( 0.823047)
no capture with block passed 0.720000 0.000000 0.720000 ( 0.714247)
block capture with block passed 5.170000 0.020000 5.190000 ( 5.194559)
$ ruby -e 'def r(a,b); (a-0.42)/(b-0.42); end; puts r(0.820000,0.690000), r(5.170000,0.720000)'
1.4814814814814816
15.833333333333334
$ ruby -e 'puts RUBY_PLATFORM,RUBY_VERSION'
x86_64-darwin13
2.2.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment