Question
Why is JavaScript executing callbacks in a for-loop so fast the first time?
The following code with callback
argument runs faster in the first loop.
const fn = (length, label, callback) => {
console.time(label);
for (let i = 0; i < length; i++) {
callback && callback(i);
}
console.timeEnd(label);
};
const length = 100000000;
fn(length, "1", () => {}) // very few intervals
fn(length, "2", () => {}) // regular
fn(length, "3", () => {}) // regular
and then I removed the third argument callback
, and their execution times are very near:
const fn = (length, label, callback) => {
console.time(label);
for (let i = 0; i < length; i++) {
callback && callback(i);
}
console.timeEnd(label);
};
const length = 100000000;
fn(length, "1") // regular
fn(length, "2") // regular
fn(length, "3") // regular
Why?