function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
r: 0,
});
}
return result;
}
const array = generateTestArray();
array.map(x => x.a + x.b)
const array = generateTestArray();
const r = [];
for (let i = 0, len = array.length; i < len; ++i) {
r[i] = array[i].a + array[i].b;
}
const array = generateTestArray();
const r = new Array(array.length);
for (let i = 0, len = array.length; i < len; ++i) {
r[i] = array[i].a + array[i].b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map | |
for | |
for (init array) |
Test name | Executions per second |
---|---|
map | 21.1 Ops/sec |
for | 30.8 Ops/sec |
for (init array) | 38.0 Ops/sec |
I'd be happy to explain the provided benchmark and its different approaches.
Benchmark Overview
The provided benchmark measures the performance of three different ways to sum up elements in an array:
map()
methodfor
loopfor
loop with initialization (i.e., creating a new array before the loop)Each test case is designed to generate a large array of 1 million elements, where each element has three properties: a
, b
, and r
. The benchmark compares the execution times of these three approaches on various browsers and devices.
Approach 1: Using the map()
method
The map()
method is a built-in JavaScript function that applies a given function to each element in an array, returning a new array with the results. In this test case, the map()
method is used to sum up the values of a
and b
for each element in the array.
Pros:
Cons:
Approach 2: Traditional for
loop
This approach uses a traditional for
loop to iterate over each element in the array and sum up its values.
Pros:
Cons:
map()
methodApproach 3: for
loop with initialization (i.e., creating a new array before the loop)
This approach is similar to the traditional for
loop, but it creates a new array before the loop to store the results.
Pros:
for
loopfor
loopCons:
Library Usage
None of the test cases use any external libraries. However, the benchmark itself uses a custom generateTestArray()
function to generate the test arrays.
Special JavaScript Features/Syntax
There are no special JavaScript features or syntax used in these benchmarks. They only rely on standard JavaScript language constructs and built-in functions like map()
, for
loops, and array indexing.
Alternative Approaches
If you want to benchmark other approaches for summing up elements in an array, here are a few ideas:
reduce()
: This method is similar to the traditional for
loop approach but uses a more concise syntax.forEach()
: This method applies a given function to each element in an array without returning a new array with results.Keep in mind that these alternative approaches may have different performance characteristics, readability, and memory usage compared to the benchmarks presented.