In this case, my guess would be that arrayLike[len++] = el
is an optimization over actualArray.push(el)
. However, after doing a simple benchmark (code provided below results), it appears that this method is actually slower than using a standard array using the push
method as well as with same construction technique.
Results (from OS X 10.5.8, FF 3.5.6) *:
push construction: 199ms (fastest)
indexed construction: 209ms
associative construction: 258ms (slowest)
In conclusion, why Closure is using an associative array in this case is beyond me. There may likely be a reason (for instance, this technique may perform better in Chrome, or less dubiously, this technique may perform better in future releases of JavaScript engines in general), but I don't see a good reason in this case.
* A mean was not provided because the times varied from test run to test run, but consistently resulted in the same order. If you're interested, you can carry it out on your own.
Benchmark code:
var MAX = 100000, i = 0,
a1 = {}, a2 = [], a3 = [],
value = "";
for ( i=0; i<1024; ++i ) {
value += "a";
}
console.time("associative construction");
for ( i=0; i<MAX; ++i ) {
a1[i] = value;
}
a1.length = i;
console.timeEnd("associative construction");
console.time("push construction");
for ( i=0; i<MAX; ++i ) {
a2.push(value);
}
console.timeEnd("push construction");
console.time("indexed construction");
for ( i=0; i<MAX; ++i ) {
a3[i] = value;
}
console.timeEnd("indexed construction");
The size and type of value
is insignificant to the test as JavaScript uses copy-on-write. A large (1kb) value
was used for the purpose of convincing those readers who are not familiar with this feature of JavaScript.