eval()可以优化吗?

编程入门 行业动态 更新时间:2024-10-26 12:29:53
本文介绍了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); }

根据规范,事件处理函数有一个对一个变量(通过执行上下文的变量绑定对象),因此只要该事件处理程序存在,该数组就会保存在内存中。但是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()可以优化吗?

本文发布于:2023-10-19 20:27:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:eval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!