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

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

问题描述

我发现在 for 循环中缓存数组的 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 JIT 人员会优化该技巧."显然这不是一个微不足道的优化,因为你可以例如在迭代过程中修改数组,但我认为考虑到我听说过的关于 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天全站免登陆