Skip to content

Instantly share code, notes, and snippets.

@rdp
Created March 15, 2010 16:17
Show Gist options
  • Select an option

  • Save rdp/332993 to your computer and use it in GitHub Desktop.

Select an option

Save rdp/332993 to your computer and use it in GitHub Desktop.
require 'benchmark'
def yields
yield
end
def named_block &block
block.call
end
class A
def go
end
def get_proc
@proc ||= proc {}
end
def named_block &block
block.call
end
def test_cached n
@proc ||= proc {}
n.times {
named_block(&@proc)
}
end
end
YO = proc {}
5.times {
Benchmark.bm do |x|
n = 100000
x.report("straight yield ") { n.times { yields {}}}
x.report("named block ") { n.times { named_block {}}}
a = A.new
b = a.method(:go)
yo = proc {}
x.report("cached proc ") { n.times { named_block(&a.get_proc) }}
x.report("cached method ") { n.times { named_block(&b) }}
x.report("local proc ") { n.times { named_block(&yo) }}
x.report("constant as proc") { n.times { named_block(&YO) }}
x.report("instance varproc") { A.new.test_cached(n) }
end
}
# it would appear that the speedup would come from a type of analysis like
#
E:\dev\digitalarchive_trunk.trunk>ruby -v speed_test.rb
ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-mingw32]
user system total real
straight yield 0.032000 0.000000 0.032000 ( 0.031250)
named block 0.297000 0.016000 0.313000 ( 0.312500) * here's the epic fail I was referring to
cached proc 0.078000 0.000000 0.078000 ( 0.078125)
cached method 0.578000 0.015000 0.593000 ( 0.593750)
local proc 0.047000 0.000000 0.047000 ( 0.046875)
constant as proc 0.047000 0.000000 0.047000 ( 0.046875)
instance varproc 0.046000 0.000000 0.046000 ( 0.046875) * if we could replace blocks with this it would help the epic fail, but not be faster than straight yield
jruby
straight yield 0.047000 0.000000 0.047000 ( 0.047000)
named block 0.078000 0.000000 0.078000 ( 0.078000)
cached proc 0.094000 0.000000 0.094000 ( 0.094000)
cached method 0.140000 0.000000 0.140000 ( 0.140000)
local proc 0.063000 0.000000 0.063000 ( 0.063000)
constant as proc 0.062000 0.000000 0.062000 ( 0.062000)
instance varproc 0.063000 0.000000 0.063000 ( 0.063000) * small speedup over named block, small loss over straight yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment