News for hackers. Stuff that matters.
Re:Introducing Swift by curveship on Monday June 02, 2014 @07:41PM (#7837241)
> In this example, the compiler could not possibly have known I was going to access x.

Right, but it knew you were going to use eval, and to support that, it had to allocate all local variables in the closure. That's why you saw this behavior. The same would happen if you used a 'with' construct.

Re:Introducing Swift by Udo on Monday June 02, 2014 @07:48PM (#7837265)
> Right, but it knew you were going to use eval, and to support that, it had to allocate all local variables in the closure.

Wow, so there is actually special handling in the engine for this? So it does static analysis whenever it can, but not in these two cases?

Re:Introducing Swift by curveship on Monday June 02, 2014 @07:57PM (#7837307)
Yes, the V8 compiler bails out of several optimizations if your function uses eval. You can see this in the profiler: functions which V8 wasn't able to optimize will have an alert sign next to them, and if you click it, it'll tell you what the issue was.
Re:Introducing Swift by anonymoushn on Monday June 02, 2014 @08:35PM (#7837460)
This is a bit troublesome!

  function f() {var x = 99; return function(a,b) {return a(b)};}
  f()(eval, 'console.log(x);')
  ReferenceError: x is not defined
  function f() {var x = 99; return function(a,b) {return eval(b)};}
  f()(eval, 'console.log(x);')
  99
  undefined
Re:Introducing Swift by curveship on Monday June 02, 2014 @08:45PM (#7837511)
Yep, this is as per spec: http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.2 . "Indirect" calls to eval (i.e. assigning eval to another variable, like you did by passing it as a param) are evaluated in terms of the global environment. "Direct" calls, like in your second example, use the local environment.
Re:Introducing Swift by Udo on Monday June 02, 2014 @08:00PM (#7837319)
Very cool, thanks for clearing that up!
Re:Introducing Swift by coldtea on Monday June 02, 2014 @08:52PM (#7837542)
Yes, and in articles describing it (v8), they explicitly warn you to not use "eval" or "with" for the performance impact.