I have a question in performance.
Assume I have a massive array of objects called records.
My goal is to create a Set (which makes sure that I have distinct values) that contains the value value of records from records that
meet a certain condition - if(rec.otherValue === 'something specific').
I have two possible ways that will yield the desired result:
Option 1:
const set = new Set();
records.foreach(rec => {
if(rec.otherValue === 'something specific'){
set.add(rec.value);
}
});
First option is straight-forward. I go through all records and add the desired value to the Set if the specific condition is met.
Option 2:
const set = new Set();
const filteredRecords = records.filter(rec => rec.otherValue === 'something specific');
filteredRecords.foreach(rec => {
set.add(rec.value);
});
Second option first filters the massive records array in order to get a much more specific array of objects (from hundreds of records to less than 10), and then addidng the desired values to the Set.
Both options yield the exact same result. My question is: which one is the best performance-wise? My goal is to make the function as fast as possible. And if there's a third, even faster option, please do share.
Testing this
I was curious about just how much faster the modern methods are, so I set up some tests on JSPerf. Here’s what I found:
forEach() method perform pretty close to each other.map() and filter() are about twice as fast as using forEach() and pushing to a new array to do the same thing.forEach() for multi-step manipulation is about twice as fast as chaining methods like filter() and map().Link to source
Benchmark for: reduce(), filter(), map(), forloop and forEach()
I tried running the benchmark multiple times and got the for loop as the slowest while forEach() and reduce() as the fastest.
There's another option you can use, with the use of reduce().
Here's an example:
let data = [
{
id: 1,
value: 'one'
}, {
id: 2,
value: 'two'
}, {
id: 3,
value: 'three'
}, {
id: 4,
value: 'four'
}, {
id: 5,
value: 'five'
},
];
// Filters IDs of odd numbers [1,3,5]
let new_arr = data.reduce((a, b) => {
if ([1,3,5].includes(b.id)) {
a.push(b.value);
}
return a;
}, []);
console.log(new_arr); // Expected Result: ['one', 'three', 'five']
// Or you can use this one Liner
let new_arr_1 = data.reduce((a, b) => a.concat(([1,3,5].includes(b.id) ? b.value: [])), []);
console.log(new_arr_1); // Expected Result: ['one', 'three', 'five']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With