I always assumed caching the length of an array in JavaScript is a good idea (especially in the condition of a for
loop) because of the expensiveness of calculating the length of an array.
Example
for (var i = 0; i < arr.length; i++) { }
// vs
for (var i = 0, arrLength = arr.length; i < arrLength; i++) { }
However, I thought perhaps the length
property is only updated on creation and alteration of the array. Therefore, reading it shouldn't be too expensive an operation as opposed to reading it stored in a variable (as opposed to other methods in other languages that may need to seek in memory to find the end of something, e.g. strlen()
in C).
I have two questions. I am also interested in how this works, so please don't hit me with the premature optimisation stick.
Assume the JavaScript engines in browsers.
- Is there any advantage to caching the
length
property of an array in JavaScript? Is there much more involved in reading a local variable over an object's property?
- Is the
length
property simply altered on creation and on shift()
and pop()
type methods that don't return a new array and otherwise simply stored as an integer?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…