[JavaScript] Shoud I have to cache my array’s length?

Happy new year!

To start this promising year, I would like to discuss about an interesting topic I saw on Twitter (@deltakosh if you want to discuss). The discussion was about array’s length access during a loop.

Simply put, should I use this:

var total = 0;
for (var i = 0; i < myArray.length; i++) {
    total += myArray[i];
}

Or that:

var total = 0;
for (var i = 0, len = myArray.length; i < len; i++) {
    total += myArray[i];
}

Should I use the .length property on every loop or should I cache it? Interesting question because almost all JavaScript code on the web have to use loops.

So pragmatically I created this small Jsperf: https://jsperf.com/arraylengthprecaching

And the result is self-explanatory:

clip_image002

Please do not be afraid by the absence of IE, this is due to some user agent sniffing changes we did_._

First point that we can note: Results are slightly the same most of the time.

On desktop configuration, browsers are doing a great work and there is almost NO difference between our two options. We can even see some devices where cached version is slower than regular version.

For instance in latest version of IE (That you can test on Windows 10 Technical preview or using https://remote.modern.ie) , we started optimizing this recently by hoisting the length load out of the loop as you can see in this post. However, it is worth nothing that optimizations have limitations and don’t always kick in.

Mobile browsers do not have (yet) the array length hoisting optimization, so it is expected that length caching performs noticeably better in a micro benchmark like this one.

To sum up, when optimizing for performance, it’s almost always better to manually hoist such things, as it provides more information – it enforces the otherwise assumption that the JIT must make and guarantee, that the length does not change inside the loop, or that the loop does not care if the length does change. But on the other hand, if the code being written is not performance sensitive, it may not be worth going out of the way to optimize it, unless it is also done for readability or some other good reason (Vyacheslav Egorov wrote an excellent post on this topic)

__

Side note: I saw people arguing that accessing .length property can be longer because JavaScript arrays are stored internally as linked list. This is not true because the chunks of an array are stored as contiguous elements for random access within the chunks, but since JavaScript allows sparse arrays, sparse arrays store several chunks in a linked list, to balance access speed and memory usage.