javascript做為用戶端的指令碼語言,一般來說都是速度是第一.要求速度就要看怎樣才會讓速度最快.
迴圈基本上所有語言中都有的,也是最常用的,它的體現,基本能代錶速度的體現.
javascript中基本分2種迴圈:for迴圈 while迴圈
for迴圈分為3種:for ++;for --;for in
while迴圈分為2種(do-while語句不考慮):while ++;while --
到底哪個快些?
隨便寫幾個測試語句,基本就能比較出最快的迴圈是哪個.
得出結論:for -- 和 while -- 應該是最快的,兩者的速度差不多,經過多次實驗,還是對比不出哪個快些;有知道內部詳 細實現的請聯絡我,謝謝啦.
for in 最慢,總以為最簡單的最快,試過後才知道.......for in 實在太慢了,令人傷心啊
step 1 : for 迴圈: < script type = " text/javascript " >
/**/ /**
*test for ++ loop;for -- loop;for in loop
*which one is the fastest one
*
*by sun 20071211
*/
var arrLength = window.prompt( " input a number for loop count " , 100000 );
document.write( " loop count : " + arrLength + " <br/> " );
var tempArr = new Array();
var tempValue;
var arrEndPosition = arrLength - 1 ;
// timer
var startTime;
var endTime;
// fill
for ( var i = arrEndPosition ; i >= 0 ; i -- ) ... {
tempArr.push(i);
}
// for ++ loop
startTime = new Date().getTime();
for ( var i = 0 ; i < arrLength ; i ++ ) ... {
tempValue = tempArr[i];
}
endTime = new Date().getTime();
document.write( " for ++ time : " + (endTime - startTime));
document.write( " <br/> " );
// for -- loop
startTime = new Date().getTime();
for ( var i = arrEndPosition ; i >= 0 ; i -- ) ... {
tempValue = tempArr[i];
}
endTime = new Date().getTime();
document.write( " for -- time : " + (endTime - startTime));
document.write( " <br/> " );
// for in loop
startTime = new Date().getTime();
for ( var i in tempArr) ... {
tempValue = tempArr[i];
}
endTime = new Date().getTime();
document.write( " for in time : " + (endTime - startTime));
</ script >
測試結果 速度: for -- < for ++ < for in(最慢)
step 2 : while 迴圈: < script type = " text/javascript " >
/**/ /**
*test while ++ loop;while -- loop
*
*by sun 20071211
*/
var arrLength = window.prompt( " input a number for loop count " , 100000 );
document.write( " loop count : " + arrLength + " <br/> " );
var tempArr = new Array();
var tempValue;