0

I have read and heard many times that .length shouldn't be used in loops.

Bad:

for (i = 0; i < myArray.length; i += 1) {}

Better:

const myLength = myArray.length;
for (i = 0; i < myLength; i += 1) {}

While I understand this concern in other languages, like PHP, which uses a standalone function to count elements. Is .length in JavaScript really calculated each time?

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
  • V8 probably takes care of it nowdays. – Joe Jan 24 '19 at 09:32
  • [Relevant answer](https://stackoverflow.com/a/32850687/1419590) – Saraband Jan 24 '19 at 09:33
  • 3
    its *value vs property lookup* debate. Though you will not save a lot by that. Its one of the micro optimization. Its always better to improve algo/logic instead – Rajesh Jan 24 '19 at 09:33
  • @Rajesh Is it also *micro* for one billion entries array? – Robo Robok Jan 24 '19 at 09:34
  • 1
    @Rajesh: if you have a billion entries, then chances is that looping through them is going to take too long, no matter what you're doing in the loop. Find an algorithm that avoids looping over all of them, if at all possible. Also: Even if the array is perfectly space-saving and the data you loop over is only a single byte, one billion entries would be one Terrabyte of memory ... – Joachim Sauer Jan 24 '19 at 09:36
  • @RoboRobok Yes. It still is micro. Having a better algo would save you lot more that saving a lookup. You can try jsPerf for this to see actual difference – Rajesh Jan 24 '19 at 09:36
  • 1
    @JoachimSauer That is exactly my point. Better algo is always better then such micro optimizations – Rajesh Jan 24 '19 at 09:37
  • So you guys are saying that `length` is NOT being calculated on the fly, right? It's just a matter of a property lookup? If so, I can't imagine myself creating a variable to just avoid a lookup, sounds very amateurish and the code would become polluted with variables very quickly. But then, why so many books say `length` should be avoided in loops? I'm sure they don't mean the property lookup. Do they misunderstand how `length` works? – Robo Robok Jan 24 '19 at 09:44
  • And by the way, is property lookup really slower? Variable lookup is also a lookup, just from a different bucket. – Robo Robok Jan 24 '19 at 10:06

0 Answers0