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 |
---|---|
[...Array(n).keys()].map(filler) | |
Array.apply(null, { length: 4 }).map(filler) | |
Array.from | |
Array(n).fill(undefined).map(filler) | |
for loop push |
Test name | Executions per second |
---|---|
[...Array(n).keys()].map(filler) | 111.6 Ops/sec |
Array.apply(null, { length: 4 }).map(filler) | 69.3 Ops/sec |
Array.from | 357.3 Ops/sec |
Array(n).fill(undefined).map(filler) | 141.3 Ops/sec |
for loop push | 436.4 Ops/sec |
This benchmark is designed to evaluate the performance of various methods for initializing an array in JavaScript using a mapping function. The filler
function takes an index and returns the square of that index, simulating a typical computation during the array initialization process.
Five individual test cases compare different methods for array initialization and mapping:
Spread Operator with Array Keys
[...Array(n).keys()].map(filler);
n-1
using the spread operator and Array.keys()
, then applies the filler
function to each index.n
values, potentially leading to inefficiency.Array.apply with Map
Array.apply(null, { length: n }).map(filler);
Function.prototype.apply
method to create an empty array with a specific length, and then maps over it with the filler
function.apply
.Array.from Method
Array.from({ length: n }, filler);
Array.from
can create a new array and apply the filler
function to each element. It generates the indices automatically.Filling an Array with Undefined and Mapping
Array(n).fill(undefined).map(filler);
undefined
values and then maps over the array with the filler
function.undefined
, which may have unnecessary memory overhead.Classic For Loop
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(filler(null, i));
}
The benchmark results show the number of executions per second for each approach:
When selecting an array initialization approach in JavaScript, several factors come into play:
for
loop demonstrates the best performance in this benchmark, particularly for larger arrays.map
and Array.from
can make code clearer and more expressive, which is beneficial for team collaboration.n
could lead to stack overflow errors and thus are less reliable.Array.from
may not be supported in older JavaScript engines.Other alternatives for array initialization might include using Array.fill
, Unshift/Concat
, or even employing libraries like Lodash, which provide utility methods for more advanced data manipulation patterns. Each of these methods balances performance and readability differently, and the best choice may depend on the specific use case and context in which you are working.