Hacker News new | past | comments | ask | show | jobs | submit login

> Is it because declaring &block means my code in the method body can now "do stuff" with `block`, whereas in the implicit case I don't have a reference so I can't do any funny business but just yield? That would make sense.

That's exactly it. With `&block`, you get a reified Proc on which you can do all kinds of stuff[0] and which you can move around. With a `yield` and an implicit block, you can't do any of that, you can just call the block. So the interpreter can bypass all the Proc reification as it knows the developer won't be able to use it, it can keep just a C-level structure instead of having to setup a Ruby-level object.

There's a not-completely-dissimilar situation with `arguments` in javascript: if you're using it, the runtime has to leave a number of optimisations off because you can do much, much more with it than with just formal arguments.

And keep in mind MRI/YARV is a relatively straightforward bytecode interpreter. It'd be interesting to see how Rubinius or JRuby fare: the should be able to compile away the reification if it's not necessary (though there's a trap: they may also have plain cheaper procs which they don't need to optimise away).

[0] http://ruby-doc.org//core-2.2.0/Proc.html has plenty of fun methods, which you can only access via a reified proc

You can create that Proc from implicit block on demand by calling `Proc.new` without a block.

At which point you eat the reification cost.

It's real easy to test too: just bench

  def a flag
    Proc.new if flag
with the flag set to `true` or `false`. Note that the proc is never actually called or returned to a possible caller, the only difference is that one reifies the proc and the other one not.

You'll get roughly the same 5x difference (with `flag=false` being the fastest) as TFA notes.

Yes. But only when you actually need it (for example to store/pass it).

Note that this was actually the original way to do so. The &block argument format was added later.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact