faster blocks

17 views
Skip to first unread message

rogerdpack

unread,
Mar 15, 2010, 1:16:47 PM3/15/10
to ruby optimization
So it turns out that blocks *are* optimizable...well, certain ones are
at least :)

It appears from

http://gist.github.com/332993

that using bound method instances isn't faster like I thought it was
for some reason. Guess I remembered poorly.

So rewriting blocks would be useful if I *knew* one was going to be
used as a named block

class A

def go &block
yield (3)
end


def yo
go {|n|
n*2
}
end
end

(in this case I could lookup at compile time see "oh that one in the
yo method looks like I'll want to optimize it").

The block has to not access any variables outside its own scope.

def yo
a = 3
go {|n|
n*n # optimizable
a*2 # not optimizable
@a*2 # optimizable
}
end

And wouldn't be able to do a "return" within it, nor would you be able
to do an eval(caller, block_instance) on it if you rewrote it (that's
pretty rare, though).

You'd convert it to something like

class A

def initialize
@yo_block_1 = proc {|n| n * 2}
end

def go &block
yield (3)
end

def yo
go &@yo_block_1
end

end

10x speedup for MRI, no speedup for jruby (which is already fast).
Hmm.

http://gist.github.com/333015

Reply all
Reply to author
Forward
0 new messages