Last active
November 21, 2023 21:16
-
-
Save LukeberryPi/d5b8dc832592ee2a4f6725f3d000037f to your computer and use it in GitHub Desktop.
comparing loops in javascript
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 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
my forEach implementation was wrong: https://chat.openai.com/share/d2ab421a-ff1f-44c0-9d43-ecf1119c07f2