函数声明和函数表达式的性能差异 [英] function declaration and function expression performance difference

查看:185
本文介绍了函数声明和函数表达式的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了



根据我遇到的几篇文章,两者都应该有类似的表现,而test2有一点优势。但这里完全相反。有人可以解释为什么这个巨大的差异吗?



编辑:我也了解他们之间的差异。请不要将其标记为或其他有关语义差异的问题,并且不会回答我关于表现的问题。



谢谢。

我猜这不是意图。



这个替代测试,我已经安排了一些事情以避免函数的重复定义,并添加了一些调用函数的其他方法。这减少了我认为由实验性噪音支配的性能差异。虽然这有时可能会有明显的差异,但我不会认为它们具有统计显着性,因为它们具有实验误差水平。换句话说,它将比赛减少到虚拟领带。



即使在两种方法之间存在一致差异的浏览器中,将函数缓存在局部变量中似乎也可以最小化定义和表达式之间的差异。 b

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.

解决方案

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.

这篇关于函数声明和函数表达式的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆