用new function(){}构造对象,而用(function(){})()调用函数-性能? [英] Constructing object with new function(){} vs. invoking function with (function(){})() - Performance?
问题描述
具有小写字母"f"的new function()`;在JavaScript中
我的直觉说,使用new关键字会比较慢.使用这两种方法有什么明显的好处?
My intuition says using the new keyword would be slower. Is there any noticeable benefit to using either method?
推荐答案
我的猜测是,函数构造函数形式(new function() { }
)比在闭包((function(){ return {}; })()
)中返回对象常量要快,因为后者似乎要比前者做更多的工作.
My guess would be that the function constructor form (new function() { }
) would be faster than returning an object literal in a closure ((function(){ return {}; })()
) because the latter seems to be doing a little more work than the former.
但是,看来我是错的,至少对于一些现代JavaScript引擎而言. 此jsPerf比较显示,文字/关闭形式在这两种方式中都快得多Chrome和Firefox.
However, it appears I am wrong, at least for a couple modern JavaScript engines. This jsPerf comparison shows the literal/closure form to be considerably faster in both Chrome and Firefox.
最终,我认为代码的正确性和程序员意图的清晰性比这种琐碎的优化(无论如何在现实世界中的JavaScript引擎之间可能会有很大的差异)更为重要.
Ultimately, I think the correctness of the code and the clarity of the intent of the programmer is more important than such a trivial optimization (which likely varies greatly between real-world JavaScript engines anyway).
这篇关于用new function(){}构造对象,而用(function(){})()调用函数-性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!