现代JavaScript JITers需要循环中的数组长度缓存吗? [英] Do modern JavaScript JITers need array-length caching in loops?

查看:200
本文介绍了现代JavaScript JITers需要循环中的数组长度缓存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在中为循环缓存数组的 length 属性的做法非常令人反感。如,

I find the practice of caching an array's length property inside a for loop quite distasteful. As in,

for (var i = 0, l = myArray.length; i < l; ++i) {
    // ...
}

至少在我看来,这个与直接的

In my eyes at least, this hurts readability a lot compared with the straightforward

for (var i = 0; i < myArray.length; ++i) {
    // ...
}

(更不用说它了由于词法范围和悬挂的性质,另一个变量泄漏到周围的函数中。)

(not to mention that it leaks another variable into the surrounding function due to the nature of lexical scope and hoisting.)

我希望能够告诉任何人这样做不要麻烦;现代JS JITers优化了这个技巧。显然,这不是一个微不足道的优化,因为你可以例如在迭代过程中修改数组,但我认为考虑到所有关于JITers及其运行时分析技巧的疯狂内容,他们现在已经达到了这个目的。

I'd like to be able to tell anyone who does this "don't bother; modern JS JITers optimize that trick away." Obviously it's not a trivial optimization, since you could e.g. modify the array while it is being iterated over, but I would think given all the crazy stuff I've heard about JITers and their runtime analysis tricks, they'd have gotten to this by now.

任何人都有这样或那样的证据?

Anyone have evidence one way or another?

是的,我也希望说这是微观优化;在你描述之前不要这样做。但并不是每个人都会听到这种理由,特别是当它成为缓存长度的习惯时,它们最终会自动完成,几乎作为一种风格选择。

推荐答案

这取决于以下几点:


  • 您是否已经证明您的代码是否花费大量时间循环

  • 您是否完全支持最慢的浏览器是否受益于数组长度缓存

  • 无论您是您的工作人员还是工作人员代码发现数组长度缓存难以阅读

从我看过的基准测试看来(例如,这里这里)IE中的表现< 9(通常是你必须处理的最慢的浏览器)从缓存数组长度中受益,所以它可能值得做。对于它的价值,我有一个缓存数组长度的长期习惯,因此很容易阅读。还有其他循环优化可以起作用,例如倒计时而不是倒计时。

It seems from the benchmarks I've seen (for example, here and here) that performance in IE < 9 (which will generally be the slowest browsers you have to deal with) benefits from caching the array length, so it may be worth doing. For what it's worth, I have a long-standing habit of caching the array length and as a result find it easy to read. There are also other loop optimizations that can have an effect, such as counting down rather than up.

以下是来自JSMentors邮件列表的相关讨论: http://groups.google.com/group/jsmentors/browse_thread/thread/526c1ddeccfe90f0

Here's a relevant discussion about this from the JSMentors mailing list: http://groups.google.com/group/jsmentors/browse_thread/thread/526c1ddeccfe90f0

这篇关于现代JavaScript JITers需要循环中的数组长度缓存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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