Is setting a variable to hold .length of objects good practice?

I’ve been caching the result of .length methods before using them in loops, so the length isn’t being calculated each loop, as I assumed this would be a performance hit.

So, instead of

for(let i = 0; i < myArr.length; i++) {

I’ve been writing

let myArrLen = myArr.length;
for(let i = 0; i < myArrLen; i++) {

I understand that sometimes this isn’t appropriate (ie; if the length of the object is likely to change during the loop), but I’m mainly wondering which is common practice, and which is considered best practice?

I’ve had a quick google around and saw a few threads on stackoverflow like this one, but I keep finding conflicting opinions on which is preferable.

Any suggestions?

A programmer friend of mine said it’s preferable to write human-readable code versus worrying about speed unless you’re having speed performance issues. Either options are likely fine for the types of programs you’re writing at the moment.

I will point out however that you are dealing with Arrays in for loops not Objects.

1 Like

The .length property of an array takes the same amount of time to get as assigning it to another variable and using it instead.

1 Like

Don’t sweat the small stuff. If it’s ever a significant performance increase to do stuff like cache the length value, you can be sure that the JS compiler has been optimized to do it for you. Focus your efforts on writing not-terrible code and you’ll be fine.