eval()可以优化吗? [英] Can eval() optimize?

查看:148
本文介绍了eval()可以优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


eval()能够更改局部变量,这对JavaScript优化器来说是个问题。


我读过javascript权威指南书。



eval()可以优化?我不明白。

解决方案

这不是 eval 优化,因为它接受一个字符串并且无法进行静态分析,因此希望通过 eval 来阻止想要优化的JavaScript引擎关于它可能执行的代码。



考虑这个函数:

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

根据规范,事件处理函数有一个对<$的引用c $ c>一个变量(通过执行上下文的变量绑定对象),因此只要该事件处理程序存在,该数组就会保存在内存中。但是JavaScript引擎可以分析事件处理程序并确定无法它可以引用 a ,从而优化变量的内容绑定对象,让数组得到垃圾回收。



但是在那里抛出一个 eval

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

现在,JavaScript引擎无法优化变量绑定的内容对象,所以它必须将大数组保留在内存中,以防 str 中包含访问它的代码。



<这只是一个具体的例子。基本点是 eval 为JavaScript引擎的优化器投入了一个伟大的大扳手,实际上必须将其关闭。


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.

解决方案

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 variable binding 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 there is no way that it can 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 variable binding object and 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 it have to turn it off.

这篇关于eval()可以优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆