Skip to content

Instantly share code, notes, and snippets.

@LukeberryPi
Last active November 21, 2023 21:16
Show Gist options
  • Save LukeberryPi/d5b8dc832592ee2a4f6725f3d000037f to your computer and use it in GitHub Desktop.
Save LukeberryPi/d5b8dc832592ee2a4f6725f3d000037f to your computer and use it in GitHub Desktop.
comparing loops in javascript
function benchmark(testName, callback) {
const startTime = performance.now();
callback();
const endTime = performance.now();
console.log(testName, `time: ${endTime - startTime}`);
}
const nums = Array(1000).fill(1);
function iterateWithMap(nums) {
return nums.map((num) => num + 1);
}
function iterateWithForLoop(nums) {
for (let i = 0; i < nums.length; i++) {
nums[i] += 1;
}
return nums;
}
function iterateWithForEach(nums) {
nums.forEach((num, index, array) => {
array[index] = num + 1;
});
return nums;
}
function iterateWithForOf(nums) {
for (let num of nums) {
num += 1;
}
return nums;
}
benchmark("map", () => iterateWithMap(nums));
benchmark("forLoop", () => iterateWithForLoop(nums));
benchmark("forEach", () => iterateWithForEach(nums));
benchmark("forOf", () => iterateWithForOf(nums));
@LukeberryPi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment