Skip to content

Instantly share code, notes, and snippets.

@taingmeng
Last active June 24, 2021 09:13
Show Gist options
  • Save taingmeng/c9e3103b54ece45b50e2b4de45a5aa02 to your computer and use it in GitHub Desktop.
Save taingmeng/c9e3103b54ece45b50e2b4de45a5aa02 to your computer and use it in GitHub Desktop.
Traditional for loop and array functions comparison
const array = [];
for (let i = 0; i < 1000000; i++) {
if (i % 2 === 0) {
array.push({ sex: 'F', name: 'Alice' });
} else {
array.push({ sex: 'M', name: 'Bob' });
}
}
// traditional for loop
const getMaleNames1 = (arr) => {
const output = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].sex === 'M') {
output.push(arr[i].name);
}
}
return output;
};
// filter and map
const getMaleNames2 = (arr) => {
return arr.filter((a) => a.sex === 'M').map((a) => a.name);
};
console.time('getMaleNames1');
getMaleNames1(array);
console.timeEnd('getMaleNames1');
console.time('getMaleNames2');
getMaleNames2(array);
console.timeEnd('getMaleNames2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment