var iterations = 10000;
res = []
for (i = 0; i < iterations; i++) {
res.push(i);
}
res = Array(iterations).fill(null).map((value, index) => index);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
fill and map |
Test name | Executions per second |
---|---|
for | 3575.7 Ops/sec |
fill and map | 8796.1 Ops/sec |
The benchmark defined in the provided JSON aims to evaluate two different approaches to initializing an array in JavaScript. Specifically, it compares using a traditional for
loop against a more modern approach using the Array.fill
method in combination with Array.map
.
Traditional for
Loop:
res = [];
for (i = 0; i < iterations; i++) {
res.push(i);
}
iterations
(10,000 in this case), pushing each index value into the array.Array.fill
and Array.map
:
res = Array(iterations).fill(null).map((value, index) => index);
iterations
) filled with null
values, and then maps over this filled array to replace each null
with the index value.Traditional for
Loop:
Pros:
Cons:
Array.fill
and Array.map
:
Pros:
Cons:
null
values stored before mapping.map
may be a barrier for some developers not accustomed to this style.From the benchmark results:
fill and map
approach has a higher execution rate of approximately 8,796 executions per second.for
loop has a significantly lower execution rate of about 3,576 executions per second.This data suggests that the modern Array.fill
and Array.map
method not only improves readability, but also outperforms the traditional loop in terms of speed in this specific context.
When choosing between these approaches, developers may want to consider:
Array.fill
and Array.map
are well-supported in most environments, developers should ensure that the target environment is compatible with these methods.Other alternatives for initializing arrays in JavaScript may include:
Using Array from
Method:
res = Array.from({ length: iterations }, (_, index) => index);
This is another modern method that creates an array directly from an iterable or array-like object, applying a mapping function for initialization.
Using the Spread Operator:
res = [...Array(iterations).keys()];
This uses the spread operator and the keys()
method to create an array of keys from an array-like object, effectively creating an array of indexes.
Each method has its own advantages and may perform differently depending on the JavaScript engine and the specifics of the use case.