I am currently creating a short javascript demo by myself just for inspect function performance purpose. The code is below:
(function(){
'use strict';
var getFunctionExecuteTime = function(myFoo) {
if(typeof myFoo !== 'function'){
return -1;
}else{
var t1 = performance.now();
myFoo();
var t2 = performance.now();
return t2-t1;
}
};
var foo = function() {
console.log('running.');
};
function foo2(){
console.log('running by foo2.');
}
console.log('function foo2 spent time: ', getFunctionExecuteTime(foo2));
console.log('function foo spent time: ', getFunctionExecuteTime(foo));
console.log('function --- spent time: ', getFunctionExecuteTime(function(){
console.log('running.');
}));
})();
Those three functions i want to test, their execute time suppose to be close, but the output from Chrome console I got is interesting, like below:
running by foo2. function foo2 spent time: 5.1000000021304
running. function foo spent time: 0.11000000085914508
running. function --- spent time: 0.115999995614402
even if I swap the order of functions, the first one always consume more time to execute, so could somebody give me a hint that what is really going on?
Quick answer:
It's the way engine V8 optimizes the Javascript code.
The first time your function run, the Javascript code is transformed directly into machine code, allows it to be executed immediately.
Another thread is called to handle optimization steps. The Javascript code is now turned into an intermediate bytecode.
The next time you call that function, the optimized code is called.
You can read more here.
Investigation steps:
Here's my investigating on Node.js environment:
Result: foo will take a longer time to run than foo2.
Result: the first call of the same function always takes a longer time to be executed than the others.
Here're 2 things come into my mind:
So, to figure out, here's a small modification to the above code:
Result:
Conclusion:
So, clearly that it's the way V8 engine works. Your
getFunctionExecuteTime
function is the thing that got optimized here.