Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created March 22, 2022 02:16
Show Gist options
  • Save redblobgames/ca9216da644273b8c7c09fa0f03c7379 to your computer and use it in GitHub Desktop.
Save redblobgames/ca9216da644273b8c7c09fa0f03c7379 to your computer and use it in GitHub Desktop.
for loop comparison - probably poor benchmarking on my part
(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