Can eval() optimize?

javascript

Solution

It's not that `eval` optimizes, it's that JavaScript engines looking to optimize get prevented from doing so by `eval`, since it accepts a string and they cannot do static analysis on the code it may execute.

Consider this function:

function foo(str) {
    var a = getAReallyBigArray();
    doSomethingWith(a);
    document.getElementById("foo").addEventListener('click', function() {
        alert(str);
    }, false);
}

According to the specification, the event handler function has a reference to the `a` variable (through the lexical environment object for the execution context) and so the array is kept in memory for as long as that event handler exists. But a JavaScript engine can analyze the event handler and determine that it definitely doesn't reference `a`, and so optimize the contents of the variable binding object and let the array get garbage collected.

But throw an `eval` in there:

function foo(str) {
    var a = getAReallyBigArray();
    doSomethingWith(a);
    document.getElementById("foo").addEventListener('click', function() {
        eval(str);
    }, false);
}

Now, it's impossible for the JavaScript engine to optimize the contents of the lexical environment object, so it has to keep the big array in memory, in case `str` has code in it that accesses it.

That's just one specific example. The fundamental point is that `eval` throws a great big spanner in the works for the JavaScript engine's optimizer, effectively making the engine turn off its optimizer for the code in which `eval` appears.

Problem

It is the ability of eval() to change local variables that is so problematic to JavaScript optimizers. I read the book javascript Definitive Guide. eval() can optimize ?? I don't understand.

Original source