Javascript: Is the length method efficient?

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.

Leave a Comment