Skip to content

Instantly share code, notes, and snippets.

@magicien
Last active April 15, 2020 18:45
Show Gist options
  • Save magicien/ce555c477ff57f75fd4ea6e14b6e2205 to your computer and use it in GitHub Desktop.
Save magicien/ce555c477ff57f75fd4ea6e14b6e2205 to your computer and use it in GitHub Desktop.
Comparing performance to filter items of an array in JavaScript
// Comparing performance to filter items of an array.
// I want to convert array data, but I don't want to include some of the data.
const N = 50000;
const data = [];
for(let i=0; i<N; i++) {
data.push(i);
}
const answer = [];
for(let i=0; i<N; i++) {
if (i % 2 == 0) {
answer.push(i);
}
}
const check = (result) => {
if (result.length !== answer.length) {
console.log('NG');
return;
}
if (!result.every((value, index) => answer[index] === value)) {
console.log('NG');
return;
}
console.log('OK');
}
// 1. map & filter
const startTime1 = new Date();
const data1 = data.map(item => {
if (item % 2) {
return null;
}
return item;
}).filter(item => item !== null);
const endTime1 = new Date();
console.log('1. map & filter: ', endTime1 - startTime1);
check(data1);
// 2. reduce
const startTime2 = new Date();
const data2 = data.reduce((arr, item) => {
if (item % 2) {
return arr;
}
return [...arr, item];
}, []);
const endTime2 = new Date();
console.log('2. reduce: ', endTime2 - startTime2);
check(data2);
// 3. forEach & push
const startTime3 = new Date();
const data3 = [];
data.forEach(item => {
if (item % 2) {
return;
}
data3.push(item);
});
const endTime3 = new Date();
console.log('3. forEach & push: ', endTime3 - startTime3);
check(data3);
// 1. map & filter: 4
// 2. reduce: 3450
// 3. forEach & push: 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment