function declaration and function expression performance difference

女生的网名这么多〃 提交于 2019-11-30 19:41:59

问题


I have used JSperf to test a small sample of code.

According to a few articles I came across, both should have similar performance with test2 having a little edge. 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.


回答1:


With the powerful optimizations JavaScript engines are using these days, Micro-benchmarks like this produce somewhat misleading results. 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; 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.




回答2:


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. 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.



来源:https://stackoverflow.com/questions/44023494/function-declaration-and-function-expression-performance-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!