javascript 函数 vs 新函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4745123/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript function vs new Function
提问by Dan
According to this benchmark http://jsperf.com/function-vs-functioncreated functions run about 1000 times faster. Can you comment this?
根据这个基准 http://jsperf.com/function-vs-function创建的函数运行速度大约快 1000 倍。你能评论这个吗?
回答by Felix Kling
- You are calling f1but notf2. I.e. your second test is doing nothing but looking up a reference.
- All the work is actually done as setup for the test.
- 你在打电话,f1但不是f2。即您的第二个测试只是查找参考。
- 所有的工作实际上都是作为测试的设置完成的。
I think what you want is actually this: http://jsperf.com/function-vs-function/2Update:On second thought, you might not want this. But nevertheless, your second test is doing nothing. You are missing the ()after f2;)
我认为你想要的实际上是这样的:http: //jsperf.com/function-vs-function/2更新:再想一想,你可能不想要这个。但是,尽管如此,您的第二个测试什么也没做。你错过了()之后f2;)
So besides new Functionbeing way slower, it is also harder to maintain the body of the function ;)
所以除了new Function速度变慢之外,维护函数体也更难;)
回答by oezi
with the new Function-syntax, for every function the JS-compiler has to be started to "eval" the function body string - this is slow and should be avoided when possible:
使用new Function-syntax,对于每个函数,JS 编译器都必须启动来“评估”函数体字符串——这很慢,应该尽可能避免:
Each time […] the Function constructor is called on a string representing source code, the script engine must start the machinery that converts the source code to executable code. This is usually expensive for performance – easily a hundred times more expensive than a simple function call, for example. (Mark ‘Tarquin' Wilton-Jones)
每次[...] 在表示源代码的字符串上调用Function 构造函数时,脚本引擎必须启动将源代码转换为可执行代码的机制。这对于性能来说通常是昂贵的——例如,很容易比简单的函数调用贵一百倍。(马克“塔昆”威尔顿-琼斯)
if you had used the search on StackOverflow, you would have found this questionwich give very good and detailed information about that.
如果您使用过 StackOverflow 上的搜索,您会发现这个问题提供了非常好的和详细的信息。
EDIT:like Martin said in one of the comments below, sometimesthe new Function-constructor is a great thing. to list some examples:
编辑:像马丁在下面的意见一说,有时在new Function-constructor是一个伟大的事情。列出一些例子:
but: in 99% of the cases where you coulduse new Function, it's a bad idea - wich means: to simply define any function that has to be like it is and doesn't have some kind of "dynamic bahavior", you should always use the "normal" function-syntax to speed up your code and avoid the eval-like functionality of new Function.
但是:在您可以使用的99% 的情况下new Function,这是一个坏主意 - 这意味着:简单地定义任何必须像它一样并且没有某种“动态行为”的函数,您应该始终使用“正常”的功能语法,加快你的代码,并避免eval的样功能new Function。

