Issue #12901 has been updated by Shyouhei Urabe.


Benoit Daloze wrote:
> Shyouhei Urabe wrote:
> > This (recomputation) sounds practically very difficult to me, if not impossible.  Much easier to avoid optimization at all when binding is used.
> 
> Indeed, I think it's only done for very simple things like arithmetic operations,
> where the value can restored from operands and recomputation has no observable side-effect.
> 
> But it's impossible to know if Kernel#binding can be used or not (due to aliasing).

True.  There are two ways to tackle this problem:

1. add a new construct that does not capture variables outside of a given block.
2. just prohibit obtaining bindings; make lambdas default optimizable.
    - optionally with something that is statically analyzable to "mark" a lambda to be "volatile", and allow obtaining bindings only within that block.

I understand Richard's proposal is #1 while Koichi suggests #2.  #2's advantage is that existing codes can benefit. #1 on the other hand won't break existing codes which might be a good property.  It seems a matter of allow or disallow binding by default.

----------------------------------------
Feature #12901: Anonymous functions without scope lookup overhead
https://bugs.ruby-lang.org/issues/12901#change-63319

* Author: Richard Schneeman
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Right now if you are writing performance sensitive code you can get a performance bump by not using anonymous functions (procs, lambdas, blocks) due to the scope lookup overhead.

https://twitter.com/apotonick/status/791167782532493312?lang=en

I would like to be able to create an anonymous function and specify I don't need it to perform the lookup when called.

I am thinking that this code:

~~~
Proc.new(scope: false) {|var| puts var }
~~~

Would be the equivalent of 

~~~
def anon(var)
  puts var
end
~~~

If you call it while trying to access something from outside of the scope it would error

~~~
var = "hello"
Proc.new(scope: false) { puts var }.call
# => NameError: undefined local variable or method `var' for main:Object
~~~

An example of a case where this could be used is found in https://github.com/rails/sprockets/pull/417. In this case we are getting rid of anonymous functions in favor of a method created with refinements. This solution works but it was not an obvious optimization. It would be convenient to have a syntax for defining anonymous functions that do not need access to caller scope.






-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>