Is reading the `length` property of an array really that expensive an operation in JavaScript?

Well, I would have said it was expensive, but then I wrote a little test @ jsperf.com and to my surprise using i<array.length actually was faster in Chrome, and in FF(4) it didn’t matter.

My suspicion is that length is stored as an integer (Uint32). From the ECMA-specs (262 ed. 5, page 121):

Every Array object has a
length property whose value is always a nonnegative integer less than 232. The value of the length property is
numerically greater than the name of
every property whose name is an array
index; whenever a property of an Array
object is created or changed, other
properties are adjusted as necessary
to maintain this invariant.
Specifically, whenever a property is
added whose name is an array index,
the length property is changed, if
necessary, to be one more than the
numeric value of that array index; and
whenever the length property is
changed, every property whose name is
an array index whose value is not
smaller than the new length is
automatically deleted. This constraint
applies only to own properties of an
Array object and is unaffected by
length or array index properties that
may be inherited from its prototypes

Phew! I don’t know if I ever get used to such language …

Finally, we always have our good old lagging behind browser. In IE (9, 8, 7) caching the length is really faster. One of many more reasons to not use IE, I say.

Leave a Comment