Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139833

Is the first execution of a function always slower than the second?

$
0
0

I just noticed that if I have the exact same function and measure it's performance, then the first execution is always slower than the second one.

I tried it several times and the result is always the same.

const myF = () => console.log("hello");

console.time("1");
myF();
console.timeEnd("1");

console.time("2");
myF();
console.timeEnd("2");

First I thought the result of the first execution is somehow cached and therefore in the second execution it is faster. But I also tried with different functions that are only slightly different. But again, the result are the same as before: The function executed first is faster than the second one.

const myF = () => console.log("hello");
const myF2 = () => console.log("world");

console.time("1");
myF(); // 1 is slower than 2
console.timeEnd("1");

console.time("2");
myF2();
console.timeEnd("2");

Here I executed the 2nd function first

const myF = () => console.log("hello");
const myF2 = () => console.log("world");

console.time("2");
myF2(); // 2 is slower than 1
console.timeEnd("2");

console.time("1");
myF();
console.timeEnd("1");

Is the way I use the console.time resp. console.timeEnd correct? If so, why would the first execution be slower than the second execution? It's probably something stupid that I missed. I can't imagine the performance of the exact same function to be dependent on which line it is executed....

Tested on Chrome 78.0; Linux 19.04


Viewing all articles
Browse latest Browse all 139833

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>