Created
March 22, 2022 02:16
-
-
Save redblobgames/ca9216da644273b8c7c09fa0f03c7379 to your computer and use it in GitHub Desktop.
for loop comparison - probably poor benchmarking on my part
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
let array = []; | |
for (let i = 0; i < 10000000; ++i) { | |
array.push({ | |
a: i, | |
b: i / 2, | |
r: 0, | |
}); | |
} | |
function whileLoop() { | |
let i = 0; | |
while (i < array.length) { | |
let x = array[i]; | |
x.r = x.a + x.b; | |
i++; | |
} | |
} | |
function forEach() { | |
array.forEach(x => { | |
x.r = x.a + x.b; | |
}); | |
} | |
function forOf() { | |
for (let x of array) { | |
x.r = x.a + x.b; | |
} | |
} | |
function forIn() { | |
for (let i = 0; i < array.length; i++) { | |
let x = array[i]; | |
x.r = x.a + x.b; | |
} | |
} | |
function forInWithCache() { | |
for (let i = 0, length = array.length; i < length; i++) { | |
let x = array[i]; | |
x.r = x.a + x.b; | |
} | |
} | |
function timeIt(fn, name) { | |
console.log("________", name); | |
for (let i = 0; i < 20; i++) { | |
let print = i === 0 ? " first time" : i === 19 ? " optimized" : ""; | |
print && console.time(name + print); | |
fn(); | |
print && console.timeEnd(name + print); | |
} | |
} | |
timeIt(forOf, "for-of"); | |
timeIt(forIn, "for-in"); | |
timeIt(forInWithCache, "for-in w/cache"); | |
timeIt(forEach, "forEach"); | |
timeIt(whileLoop, "while loop"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment