Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

And yes, I too wish it would suffice to say "that's a micro-optimization; don't do that until you profile." But not everyone listens to that kind of reason, especially when it becomes a habit to cache the length and they just end up doing so automatically, almost as a style choice.

like image 367
Domenic Avatar asked Jun 07 '11 07:06

Domenic


People also ask

How do you use array length in a for loop?

As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0). Using this loop you can search if a specific value is present in the array or not.

Is find faster than for loop JavaScript?

It is fairly obvious that the native find() function is faster than a loop algorithm.


1 Answers

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

like image 101
Tim Down Avatar answered Oct 21 '22 15:10

Tim Down