Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Is the length method efficient?

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!

like image 609
santiagobasulto Avatar asked Mar 06 '12 21:03

santiagobasulto


People also ask

Why we use length in JS?

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.

Why length in JavaScript is not a function?

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 .

Is length a method or property in JavaScript?

The length property returns the number of formal parameters of the given function.

Is JavaScript length 0 based?

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.


1 Answers

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.

like image 123
josh3736 Avatar answered Sep 21 '22 03:09

josh3736