var testArray = []
for(var i=0;i<100000;i++){
testArray.push({ id: i, val: Math.random()});
}
var vals = testArray.map((a) => {return 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() | 532.8 Ops/sec |
Using traditional for loop | 441.9 Ops/sec |
Using ES6 for..of | 501.1 Ops/sec |
This benchmark tests the efficiency of three different ways to extract the val
property from an array of objects in JavaScript:
1. Using Array.prototype.map()
:
.map()
function which iterates over each element in the array and applies a provided function to it, returning a new array with the results.2. Using a traditional for
loop:
for
loop to iterate over the indices of the array and access each element individually..map()
, can be harder to read, and generally slower due to manual iteration.3. Using ES6 for...of
loop:
for...of
loop, which iterates directly over the values of the array rather than its indices. for
loop, can be slightly faster in some cases..map()
.Other Alternatives:
reduce()
: While not as directly applicable here, JavaScript's reduce()
function could be used to accumulate all the val
properties into a single array. This would be less efficient for extracting individual values but useful for other tasks.Let me know if you have any more questions!