Created
September 12, 2020 16:09
-
-
Save antonkatz/6b0911c85ddadae39c434bf8ac32b340 to your computer and use it in GitHub Desktop.
Performance of for-of given an array vs a generator
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 getNumberArray(maxValue) { | |
const a = []; | |
let i = 0 | |
for (i = 0; i < maxValue; i++) { | |
a.push(i); | |
} | |
return a; | |
} | |
function* getNumberGenerator(maxValue) { | |
let i = 0; | |
for (i = 0; i < maxValue; i++) { | |
yield i; | |
} | |
} | |
function formatNumbers(strings, ...values) { | |
let result = ""; | |
for (var i = 0; i < strings.length; i++) { | |
result += strings[i]; | |
if (i < values.length) { | |
if (typeof values[i] === "number") { | |
result += formatNumber(values[i]); | |
} | |
else { | |
result += values[i]; | |
} | |
} | |
} | |
return result; | |
} | |
function formatNumber(x) { | |
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); | |
} | |
function runTest(testName, numIterations, funcToTest) { | |
console.log(`Running ${testName}...`); | |
let dummyCalculation; | |
const startTime = Date.now(); | |
const initialMemory = process.memoryUsage(); | |
const iterator = funcToTest(numIterations); | |
for (let val of iterator) { | |
dummyCalculation = numIterations - val; | |
} | |
const finalMemory = process.memoryUsage(); | |
// note: formatNumbers can be found here: https://jsfiddle.net/onz1ozjq/ | |
console.log(formatNumbers `Total time: ${Date.now() - startTime}ms`); | |
console.log(formatNumbers `Rss: ${finalMemory.rss - initialMemory.rss}`); | |
console.log(formatNumbers `Heap Total: ${finalMemory.heapTotal - initialMemory.heapTotal}`); | |
console.log(formatNumbers `Heap Used: ${finalMemory.heapUsed - initialMemory.heapUsed}`); | |
} | |
runTest("Array", 100000000, getNumberArray) | |
runTest("Generator", 100000000, getNumberGenerator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on my machine
Running Array...
Total time: 4,022ms
Rss: 2,728,939,520
Heap Total: 2,726,199,296
Heap Used: 2,704,236,368
Running Generator...
Total time: 2,541ms
Rss: 851,968
Heap Total: 0
Heap Used: -5,073,968