Skip to content

Instantly share code, notes, and snippets.

@laat
Created March 28, 2022 08:15
Show Gist options
  • Save laat/dfa7bc71a3adaa622fd291905e0550c7 to your computer and use it in GitHub Desktop.
Save laat/dfa7bc71a3adaa622fd291905e0550c7 to your computer and use it in GitHub Desktop.
const arr = [1, 4, 4, 54, 56, 54, 2, 23, 6, 54, 65, 65];
const reduceSum = arr => arr.reduce((acc, val) => acc + val);
const forEachSum = arr => {
let sum = 0;
arr.forEach(el => sum += el);
return sum;
};
const forSum = arr => {
let sum = 0;
for (let i = 0; i < arr.length; i++ ) sum += arr[i];
return sum;
}
const forOfSum = arr => {
let sum = 0;
for (const i of arr) sum += i;
return sum;
}
const iterations = 1000000000;
console.time('reduce');
for(let i = 0; i < iterations; i++){
let sumReduce = reduceSum(arr);
};
console.timeEnd('reduce');
console.time('forEach');
for(let j = 0; j < iterations; j++){
let sumForEach = forEachSum(arr);
};
console.timeEnd('forEach');
console.time('forSum');
for(let k = 0; k < iterations; k++){
let sumForEach = forSum(arr);
};
console.timeEnd('forSum');
console.time('forOfSum');
for(let j = 0; j < iterations; j++){
let sumForEach = forOfSum(arr);
};
console.timeEnd('forOfSum');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment