Skip to content

Instantly share code, notes, and snippets.

@Hamzali
Created March 31, 2018 11:08
Show Gist options
  • Save Hamzali/dc564c69c09509a74706da71d1b3aceb to your computer and use it in GitHub Desktop.
Save Hamzali/dc564c69c09509a74706da71d1b3aceb to your computer and use it in GitHub Desktop.
Node Iteration methods
const NS_PER_SEC = 1e9;
const elapsedTimeMs = diff => (((diff[0] * NS_PER_SEC) + diff[1]) / 1e6);
const arr = [];
const arrLen = 10000;
let i = 0;
console.log("Iteration count: " + arrLen);
let startTime = process.hrtime();
while(i < arrLen) {
arr[i] = i * Math.random() % 100;
i++
}
console.log(`WHILE: ${elapsedTimeMs(process.hrtime(startTime))} ms`);
startTime = process.hrtime();
for (let j = 0; j < arrLen; j++) {
arr[i] = arr[i] * Math.random() % 100;
}
console.log(`FOR: ${elapsedTimeMs(process.hrtime(startTime))} ms`);
startTime = process.hrtime();
for(let elem in arr) {
elem = elem * Math.random() % 100;
}
console.log(`FOR IN: ${elapsedTimeMs(process.hrtime(startTime))} ms`);
startTime = process.hrtime();
arr.forEach((elem, key) => {
arr[key] = elem * Math.random() % 100;
});
console.log(`FOREACH: ${elapsedTimeMs(process.hrtime(startTime))} ms`);
startTime = process.hrtime();
const newArr = arr.map(elem => elem * Math.random() % 100);
console.log(`MAP: ${elapsedTimeMs(process.hrtime(startTime))} ms`);
// reduce, some and other array methods are like map.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment