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();
for(const x of array) {
x.r = x.a + x.b;
}
const array = generateTestArray();
array.map(x => x.a + x.b)
const array = generateTestArray();
const r = new Array(array.length);
for (let i = 0; i < array.length; ++i) {
r[i] = array[i].a + array[i].b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for..of | |
.map | |
.for (init array) |
Test name | Executions per second |
---|---|
for..of | 6.4 Ops/sec |
.map | 7.2 Ops/sec |
.for (init array) | 8.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided JSON represents three test cases that compare the performance of different approaches to iterate over an array in JavaScript:
for..of
: This is a modern JavaScript syntax introduced in ECMAScript 2015 (ES6). It allows iterating over arrays using a for...of
loop, which is more concise and expressive than traditional loops..map()
: The .map()
method applies a transformation function to every element of an array and returns a new array with the results. This approach can be useful when you need to perform an operation on each element without modifying the original array.for (init array)
: This is a traditional loop syntax that uses a variable to keep track of the current index in the array.Now, let's discuss the pros and cons of each approach:
for..of
:.map()
**:for (init array)
**:Other considerations:
generateTestArray()
function is used to create a sample array for each test case, ensuring that all implementations are working with identical data.Some notable libraries and features used in these tests include:
Special JavaScript features or syntax used in these tests include:
for...of
loop.map()
Other alternatives to consider:
while
loops or recursive functions.lodash.each()
or ramda.iterate()
.Keep in mind that the performance differences between these approaches can vary depending on specific use cases and environments. MeasureThat.net's benchmarking framework helps to identify which approach is fastest under different conditions.