Always pre-allocate arrays in Javascript

RMAG news

If you ever implemented a dynamic array in low level languages like C++ you allocate a chunk of memory for several elements at once, when there’s no more space for new elements you allocate a new chunk. I guess this is valid and for Javascript arrays. Allocation of a memory on the heap is an expensive operation, so if we follow the rule:

When the final size of an array’s is known during creation of the array – allocate it:

const arr = Array(knownSize);

This immediately boosts your Javascript speed:

let $length = 10;
const arr = Array.from({length: $length}, (_, i) => i);

// @benchmark non pre-allocated
{
const result = [];
for(let i = 0; i < arr.length; i++){
result.push(arr[i]);
}
result;
}

// @benchmark pre-allocated
{
const result = Array(arr.length);
for(let i = 0; i < arr.length; i++){
result[i] = arr[i];
}
result;
}

// @benchmark Array#map
arr.map(i => i);

` Chrome/125
———————————————————————————————–
> n=10 | n=100 | n=1000 | n=10000
pre-allocated ■ 1.00x x10m 85 | ■ 1.00x x10m 669 | ■ 1.00x x1m 474 | ■ 1.00x x100k 560
Array#map 1.69x x10m 144 | 1.79x x1m 120 | 2.15x x100k 102 | 3.20x x10k 179
non pre-allocated 3.22x x10m 274 | 3.57x x1m 239 | 4.11x x100k 195 | 3.66x x10k 205
———————————————————————————————– `

` Firefox/126
———————————————————————————————
> n=10 | n=100 | n=1000 | n=10000
pre-allocated ■ 1.00x x10m 227 | ■ 1.00x x1m 162 | ■ 1.00x x100k 192 | ■ 1.00x x10k 208
non pre-allocated 1.44x x10m 327 | 1.45x x1m 235 | 1.16x x100k 222 | 1.53x x10k 319
Array#map 1.46x x10m 332 | 1.06x x1m 172 | 1.73x x100k 333 | 2.17x x10k 452
——————————————————————————————— `

Open in the playground

Leave a Reply

Your email address will not be published. Required fields are marked *