为什么相同的for循环不同的时间

Why different time for same for loop

本文关键字:时间 循环 for 为什么      更新时间:2023-09-26

我在Chrome控制台运行以下代码,并获得不同的执行时间。

我创建了两个具有相同主体的函数。第一个是函数声明,第二个是函数表达式。

var t= new Date().getTime();
function fun1(){  
    for( i=0; i < 1000000; i ++) 
    {
        a=i;
     };
}; 
fun1();
console.log(new Date().getTime() - t);  // nearly 2ms;
t= new Date().getTime();
var fun2 = function (){  
    for(i=0; i < 1000000; i ++) 
    {
       a=i;
    };
 }; 
 fun2();
console.log(new Date().getTime() - t); //nearly 900ms

为什么相同的循环有不同的行为?

控制台代码在Google Chrome中使用语句包装在中。

function fun1() { 
    // code
}

fun1是声明的,它运行在 block

之外
var fun2 = function () {
    //code
}

fun2是表达式,运行在V8下不可优化

表达式和声明在"non-console"模式下具有相同的性能:)