i'm doing some javascript coding and I was wondering if the length method is "precomputed", or remembered by the JS engine.
So, the question is:
If I'm checking really often for an array length, and supposing that i'm not changing it (making it immutable through a closure), should I precompute the length method and store it in some variable?
Thanks!
The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings.
The "length is not a function" error occurs when we try to invoke the length property like a function instead of accessing it using dot notation. To solve the error, access the length property without parenthesis, e.g. arr. length .
The length property returns the number of formal parameters of the given function.
JavaScript arrays are zero-based. The JavaScript array “length” property returns the number of elements in an array, but it is a one-based value.
As always, the answer is "it depends".
Let's test native arrays with a million-element array:
for (var i = 0; i < arr.length; i++); var len=arr.length; for (var i = 0; i < len; i++);
http://josh3736.net/images/arrlen.png
Chrome and Firefox optimize the property accessor to be as efficient as copying the length to a local variable. IE and Opera do not, and are 50%+ slower.
However, keep in mind that the test results' "ops/second" means number of complete iterations through an array of one million elements per second.
To put this in perspective, even in IE8 (the worst performer in this bunch)—which scored .44 and 3.9 on property access and local variable (respectively)—the per-iteration penalty was a scant 2 µs. Iterating over a thousand items, using array.length
will only cost you an extra 2 ms. In other words: beware premature optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With