简体   繁体   English

函数声明和函数表达式性能差异

[英]function declaration and function expression performance difference

I have used JSperf to test a small sample of code .我使用JSperf测试了一小部分代码

在此处输入图片说明

According to a few articles I came across, both should have similar performance with test2 having a little edge.根据我遇到的几篇文章,两者应该具有相似的性能,而 test2 有一点优势。 But here it's the complete opposite.但这里完全相反。 Can someone explain why the huge difference?有人可以解释为什么会有巨大的差异吗?

Edit : I also understand the differences between both of them.编辑:我也了解它们之间的差异。 Please don't mark this as a duplicate of this or other questions which talk about the semantic differences and do not answer my question regarding performance.请不要将此标记为这个或其他讨论语义差异的问题的重复,并且不回答我关于性能的问题。

Thank you.谢谢你。

With the powerful optimizations JavaScript engines are using these days, Micro-benchmarks like this produce somewhat misleading results.随着 JavaScript 引擎如今使用的强大优化功能,像这样的微基准测试会产生一些误导性的结果。 For example, I'm guessing what you were trying to measure is function call overhead.例如,我猜您要测量的是函数调用开销。 But it looks like the way your code is written, you may be (re)defining the function definition and/or symbol lookup once for every 10 times you execute it;但看起来你的代码是这样编写的,你可能每执行 10 次就(重新)定义一次函数定义和/或符号查找; I'm guessing that wasn't the intent.我猜这不是本意。

In this alternative test , I've arranged things to avoid repeated definition of the function, and added a few other ways of invoking the functions.这个替代测试中,我安排了一些东西来避免函数的重复定义,并添加了一些其他调用函数的方法。 This reduces the difference in performance to something I'd consider dominated by experimental noise.这将性能差异减少到我认为由实验噪声主导的东西。 While this there may sometimes be apparent differences but I wouldn't consider them statistically significant given the experimental error levels.虽然这有时可能存在明显差异,但考虑到实验误差水平,我不会认为它们具有统计学意义。 In other words, it reduces the contest to a virtual tie.换句话说,它将比赛减少到虚拟平局。

Even in browsers where there's a consistent difference between approaches, caching the function in a local variable seems to minimize the difference between definition and expression.即使在方法之间存在一致差异的浏览器中,将函数缓存在局部变量中似乎可以最大限度地减少定义和表达式之间的差异。

I also understand the differences between both of them.我也明白两者的区别。

Do you also understand these semantic differences ?你也理解这些语义差异吗?

Notice that jsPerf puts your code inside a tight loop whose execution time is measured.请注意,jsPerf 将您的代码置于一个紧密循环中,该循环会测量执行时间。 The function declaration requires the creation of a block scope for each iteration, which slows the test down considerably.函数声明需要为每次迭代创建一个块作用域,这会大大减慢测试速度。 That is hardly what you were trying to measure.这几乎不是你想要衡量的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM