In JS are the lengths of an array cached or does it depend on the different engines/browsers?
Normally I’d assume that browsers’ JS engines are pretty dumb and cache the length of arrays, for example:
var a = [ ];
var l = l;
function arrayPush(i)
{
l = a.push( i );
}
function arrayPop()
{
var r = a.pop();
l = a.length;
return r;
}
(as a brief example, of course it’ll be silly to replicate every array function but if it speeds stuff up it then it’s worth it)
The array length is cached. It is updated each time the array is manipulated.
When you invoke the
.push()method on the array, the array length is updated in step 6 of the algorithm:Source: http://es5.github.com/x15.4.html#x15.4.4.7
When you invoke the
.pop()method of an array, the array length is updated in step 5.d of the algorithm:Source: http://es5.github.com/x15.4.html#x15.4.4.6
When you assign a value to the array at an given index, the
[[DefineOwnProperty]]internal method is invoked. The array length is updated in step 4.e.ii of the algorithm:Source: http://es5.github.com/x15.4.html#x15.4.5.1