It is a commonly recommended practice to cache array lengths while doing for
loops and get better performance. Seriously, is that a thing though?
Typical for
loop
In a typical for
, you calculate length, iterate and you are done.
|
|
Cache for
loop
Rather than use a typical array length condition, you first find the length and use that variable in all comparisons. This should save time to call the length
method each and every time.
|
|
At least for me, there was no observable difference in caching the array length for 1e7
values in the array. I could not see anything different for other types of arrays like strings, boolean, or an object. The comparison needs better tests on better servers - a thing to do for some other time.
But, overall the array length by itself may not really be contributing significantly to performance problems in the overall scheme of things. Or, V8 may have been optimised the heck out to really care about the humble array length when used in for
comparison.