Skip to content

Instantly share code, notes, and snippets.

@jrson83
Forked from chathurawidanage/array_performance.js
Created October 18, 2023 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrson83/be03ff2ae0baebf3a94059dc52a9d06d to your computer and use it in GitHub Desktop.
Save jrson83/be03ff2ae0baebf3a94059dc52a9d06d 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]
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