runtime of loops

Why that variation occurs between for, for...of and forEach? I'm posting here because I was running it in a "nodejs env"
No description
5 Replies
Pi, a future fluent jp speaker
Code:
const iterations = 1000000;

const myArray = Array.from(Array(iterations).keys());
let total1 = 0;
const start1 = performance.now(); // Looping method will be here

for (let i = 0; i < myArray.length; i++) {
total1 += myArray[i];
}

const ends1 = performance.now();


console.log(`for: It took ${ends1 - start1} ms. `);

let total2 = 0;
const start2 = performance.now(); // Looping method will be here

for (const item of myArray) {
total2 += item;
}

const ends2 = performance.now();



console.log(`for-of: It took ${ends2 - start2} ms. `);

let total3 = 0;
const start3 = performance.now(); // Looping method will be here

myArray.forEach((data) => total3 += data)

const ends3 = performance.now();



console.log(`forEach: It took ${ends3 - start3} ms. `);
const iterations = 1000000;

const myArray = Array.from(Array(iterations).keys());
let total1 = 0;
const start1 = performance.now(); // Looping method will be here

for (let i = 0; i < myArray.length; i++) {
total1 += myArray[i];
}

const ends1 = performance.now();


console.log(`for: It took ${ends1 - start1} ms. `);

let total2 = 0;
const start2 = performance.now(); // Looping method will be here

for (const item of myArray) {
total2 += item;
}

const ends2 = performance.now();



console.log(`for-of: It took ${ends2 - start2} ms. `);

let total3 = 0;
const start3 = performance.now(); // Looping method will be here

myArray.forEach((data) => total3 += data)

const ends3 = performance.now();



console.log(`forEach: It took ${ends3 - start3} ms. `);
Jochem
Jochem10mo ago
I don't know too much about the internal workings of JS, but the foreach calls a callback function rather than just looping over a block of code. That's got more overhead. I'm assuming for-of has a similar issue
Pi, a future fluent jp speaker
What is even more weird is that the results also changes depending on the increase or decrease of amount of iterations For 10.000 iterations, forEach was the winner
Jochem
Jochem10mo ago
I would mostly like to point out that, while it's fine to wonder about this stuff and want to know the reasons, it's not worth thinking about when you're writing production code no one is going to notice a 15ms delay in processing, and you're just measuring the overhead of the loop anyway, the real slowdown would come from the potentially complicated body of the loop (however you run it) rather than the mechanism of the loop itself what matters much, much more than this level of performance futzing, is readable code. Write what you think is readable, and worry about the performance if you see a hit. You can always profile your code and see where the slowdown happens if it's ever noticeable
Pi, a future fluent jp speaker
It makes sense
Want results from more Discord servers?
Add your server