Do modern JavaScript JITers need array-length caching in loops?

后端 未结 3 839
滥情空心
滥情空心 2020-12-02 00:06

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.         


        
3条回答
  •  北海茫月
    2020-12-02 00:34

    It depends on a few things:

    • Whether you've proven your code is spending significant time looping
    • Whether the slowest browser you're fully supporting benefits from array length caching
    • Whether you or the people who work on your code find the array length caching hard to read

    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.

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

提交回复
热议问题