Skip to content

Instantly share code, notes, and snippets.

@JaoodxD
Last active October 20, 2023 17:48
Show Gist options
  • Save JaoodxD/031f35c24ea9872f9ea029a7e33f12d9 to your computer and use it in GitHub Desktop.
Save JaoodxD/031f35c24ea9872f9ea029a7e33f12d9 to your computer and use it in GitHub Desktop.
15x perf difference
var arr = new Array(100).fill(0).map((e, i) => i);
var res = 0
function myFor(arr) {
for (let j = 0; j < 10_000_000; j++) {
for (let index = 0; index < arr.length; index++) {
res += arr[index];
}
}
}
for (let c = 0; c < 5; c++) {
console.time('for')
myFor(arr)
console.timeEnd('for') // ~12600ms
}
console.log(res);
var arr = new Array(100).fill(0).map((e, i) => i);
var res = 0
function myFor(arr) {
var tempSum = 0
for (let j = 0; j < 10_000_000; j++) {
for (let index = 0; index < arr.length; index++) {
tempSum += arr[index];
}
}
res += tempSum;
}
for (let c = 0; c < 5; c++) {
console.time('for')
myFor(arr)
console.timeEnd('for') // ~750ms
}
console.log(res);
'use strict';
var arr = new Array(100).fill(0).map((e, i) => i);
var res = 0
function myFor(arr) {
for (let j = 0; j < 10_000_000; j++) {
res += arr.reduce((acc, n) => acc + n, 0);
// for (let index = 0; index < arr.length; index++) {
// res += arr[index];
// }
}
}
for (let c = 0; c < 5; c++) {
console.time('for')
myFor(arr)
console.timeEnd('for') // ~840ms
}
console.log(res);
'use strict'
var arr = new Array(100).fill(0).map((e, i) => i)
var res = 0
function myFor (arr) {
let sum = 0
for (let j = 0; j < 10_000_000; j++) {
sum += arr.reduce((acc, n) => acc + n, 0)
}
res += sum
}
for (let c = 0; c < 5; c++) {
console.time('for')
myFor(arr)
console.timeEnd('for') // ~730ms
}
console.log(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment