var n = 100000; // 100k
function filler(v, i) {
return i ** 2;
}
[Array(n).keys()].map(filler);
Array.apply(null, { length: n }).map(filler);
Array.from({ length: n }, filler);
Array(n).fill(undefined).map(filler)
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(filler(null, i));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread operator | |
Array apply | |
Array from | |
Array fill | |
For loop push |
Test name | Executions per second |
---|---|
Spread operator | 91.7 Ops/sec |
Array apply | 128.4 Ops/sec |
Array from | 119.8 Ops/sec |
Array fill | 224.9 Ops/sec |
For loop push | 235.3 Ops/sec |
The provided benchmark tests various methods of initializing an array in JavaScript, specifically comparing different ways to achieve functionality similar to Python's list comprehension. The common goal of all methods is to create an array with values based on the index, calculated using the filler
function, which returns the square of the index. Here’s a breakdown of what is being tested, the options being compared, and their pros and cons.
Spread Operator:
[...Array(n).keys()].map(filler);
...
) creates an iterable range of indices.Array.apply:
Array.apply(null, { length: n }).map(filler);
Function.prototype.apply
to create a new array-like object where the map
function can be applied. This is a commonly used technique to create an array with specific lengths.Array.from:
Array.from({ length: n }, filler);
Array.fill:
Array(n).fill(undefined).map(filler);
fill
which does not create actual populated indices; thus, it could potentially result in more overhead compared to Array.from
.For Loop with push:
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(filler(null, i));
}
push
operations compared to other methods that initialize the size of the array upfront.Array.from
as the fastest with approximately 1218 executions per second, making it the optimal choice for initializing arrays in this context. For loop push
and Array fill
methods follow, showing moderate performance.Spread operator
and Array apply
methods perform the weakest, with the Spread operator exceeding the call stack limit at large sizes, making it less viable for high-performance applications._.range
combined with _.map
to create and manipulate arrays. This can offer cleaner syntax and additional functionalities but introduces a dependency.Int32Array
, Float64Array
, etc.) in JavaScript can provide more efficient memory usage and performance.In summary, the benchmark highlights various JavaScript approaches to array initialization, demonstrating their performance characteristics and usage scenarios. Choosing the right approach involves evaluating the specific needs of the application, considering both performance and clarity.