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.