Although it is necessary in Java, it is entirely pointless to
specify the length of an array ahead of time in JavaScript. [...]
Rather, you can just set up an empty array and allow it to grow as
you fill it in. Not only is the code shorter, but it runs faster too.
Faster? That ought to raise suspicion. JS's dynamic hash-arrays are neat, but now they're supposed to be immune from the laws that govern memory allocation in any other language?As it happens, I had occasion to test this a few months ago.
function preallocate(len) {
var arr = new Array(len);
for (var n = 0; n
On my machine, noPreallocate is 4% faster in FF, but it's 15% slower in IE8 and a whopping 70% slower in Chrome.