Last active
October 18, 2023 02:58
-
-
Save chathurawidanage/f6536d5dc8577d3e7d205902bcb71ea9 to your computer and use it in GitHub Desktop.
Iterating over javascript arrays | Performance comparison [https://gists.cwidanage.com/2019/11/how-to-iterate-over-javascript-arrays.html]
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
const { PerformanceObserver, performance } = require('perf_hooks'); | |
let arraySize = 1000000; | |
let iterations = 100; | |
console.log("Starting performance test with %d array size and %d iterations", arraySize, iterations); | |
let values = { | |
FORIN: 0, | |
FOROF: 0, | |
FOREACH: 0, | |
JUST_FOR: 0 | |
} | |
const obs = new PerformanceObserver((items) => { | |
let entry = items.getEntries()[0]; | |
console.log(entry.name, entry.duration); | |
values[entry.name] += entry.duration; | |
performance.clearMarks(); | |
}); | |
obs.observe({ entryTypes: ['measure'] }); | |
function generateArray() { | |
let arr = []; | |
for (let i = 0; i < arraySize; i++) { | |
arr[i] = 'val' + i; | |
} | |
return arr; | |
} | |
for (let i = 0; i < iterations; i++) { | |
let arr = generateArray(); | |
//foreach | |
performance.mark('A'); | |
arr.forEach((val) => { | |
let x = val + 1; | |
}); | |
performance.mark('B'); | |
performance.measure('FOREACH', 'A', 'B'); | |
//For In | |
performance.mark('A'); | |
for (const val in arr) { | |
let x = val + 1; | |
} | |
performance.mark('B'); | |
performance.measure('FORIN', 'A', 'B'); | |
//For Of | |
performance.mark('A'); | |
for (const val of arr) { | |
let x = val + 1; | |
} | |
performance.mark('B'); | |
performance.measure('FOROF', 'A', 'B'); | |
//Just for | |
performance.mark('A'); | |
for (let i = 0; i < arr.length; i++) { | |
let x = arr[i] + 1; | |
} | |
performance.mark('B'); | |
performance.measure('JUST_FOR', 'A', 'B'); | |
} | |
console.log(Object.entries(values).sort((a, b) => { | |
return a[1] - b[1]; | |
}).map(obj => { | |
obj[1] /= iterations; | |
return obj; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment