var testArray = []
for(var i=0;i<100000;i++){
testArray.push({ id: i, val: Math.random()});
}
var vals = testArray.map(a => a.val);
var vals=[];
for(var i=0;i<testArray.length;i++){
vals.push(testArray[i].val);
}
var vals=[];
for(var item of testArray){
vals.push(item.val);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using Array.prototype.map() | |
Using traditional for loop | |
Using ES6 for..of |
Test name | Executions per second |
---|---|
Using Array.prototype.map() | 484.9 Ops/sec |
Using traditional for loop | 466.3 Ops/sec |
Using ES6 for..of | 458.9 Ops/sec |
Let's dive into the benchmark.
The provided JSON represents a JavaScript microbenchmarking test case on MeasureThat.net. The goal of this benchmark is to compare the performance of three different approaches for extracting the val
property from an array of objects: traditional for loops, the Array.prototype.map()
method with arrow function syntax, and the for...of
loop.
Here's a brief overview of each approach:
var vals = [];
for (var i = 0; i < testArray.length; i++) {
vals.push(testArray[i].val);
}
Pros: Simple and easy to understand. Cons: Can be slower due to the overhead of the explicit loop control and array indexing.
Array.prototype.map()
method with arrow function syntax:var vals = testArray.map(a => a.val);
Pros: Concise and expressive, leveraging the optimized map()
method. The arrow function syntax can also reduce memory allocation overhead.
Cons: May incur additional overhead due to the creation of an intermediate array (unless explicitly using map
's callback option).
for...of
loop:var vals = [];
for (const item of testArray) {
vals.push(item.val);
}
Pros: More concise and modern than traditional for loops, with improved readability. Cons: May have slightly slower performance due to the new syntax's parsing overhead.
Now, let's consider other alternatives:
map()
, other native methods like forEach()
or reduce()
could be used for this benchmark. However, these might not provide a significant performance difference.Array.prototype.forEach()
with a custom callback) could offer an alternative approach. However, their performance would likely be comparable to the traditional for loop.The benchmark measures the execution speed of each approach, which is reflected in the ExecutionsPerSecond
value. The browser and device platform information helps to understand the performance characteristics on different hardware configurations.