3

最初にこれを実行します(クロムで):

var start;
var end;

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

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

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

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

出力: 次に、これを実行します。delay:2028

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();

出力:delay:8

関数にラップすると、同じコードの時間が短くなるのはなぜですか?

nodeでも同じくらい(6と6)かかりましたが、nodeはchromeでV8エンジンを使っていますよね?

4

2 に答える 2

3

関数では、すべての変数が閉鎖されているためです。関数 JavaScript インタープリターがないと、最初にグローバルスコープで変数を見つけようとします。

于 2012-06-22T12:34:32.010 に答える
2

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.

于 2012-06-22T15:24:34.967 に答える