Search code examples
javascriptgoogle-chromeexecute

JavaScript: Same code take different time to execute


First i run this (in chrome):

var start;
var end;

start = (new Date()).getTime();

for(var i=0;i<10e5;i++);

end = (new Date()).getTime();

console.log('delay:' + (end-start));

Output: delay:2028
Then I run this:

function foo() {
    var start;
    var end;

    start = (new Date()).getTime();

    for(var i=0;i<10e5;i++);

    end = (new Date()).getTime();

    console.log('delay:' + (end-start));
}

foo();

Output: delay:8

Why took the same code shorter time when wrappered in a function?

In node it took the same time (6 and 6), but node uses the V8 engine by the chrome isn't it?


Solution

  • I think the fact that this behavior only appears in the console is extremely telling. I suspect it has to do with how the V8 engine reducing the script down to native code.

    Point #1: I suspect that scope is not the cause of the slowdown:

    function foo() {
        start = (new Date()).getTime();
        for(i=0;i<10e5;i++);
        end = (new Date()).getTime();
        console.log('delay:' + (end-start));
    }
    

    This code uses start, end, and i in the global scope. If searching through the global scope really was the bottleneck, then this code should also run slowly, because it has no local variables in the function.

    Point #2: If you put your code in an actual web page, it runs very quickly either way. This suggests to me that running code in the console is the source of the slowdown.

    Ordinarily, on a web page, the V8 engine assembles JavaScript into native binary code so it runs very quickly. However, I suspect that code run from the console is not compiled (or is perhaps compiled line-by-line as it is run, which itself incurs a time cost). When a function definition is entered, though, the function is compiled, in its entirety, before it is run for the first time. By the time the program flow reaches the foo() call, the function foo has already been compiled into native code. Thus the function runs quickly because it has been pre-compiled, but the raw code in the console has not been pre-compiled, so it runs slowly.

    This is largely speculation, but so is every answer to this question. This is the only explanation I can possibly devise that accounts for both points #1 and #2 above.