循環是大多數編程語言都具備的基本功能,JS也不例外,不同之處在于JS是解釋型語言,運行于瀏覽器環境中,客戶端的軟硬件條件會對JS執行效率產生很大的影響。然而客戶端環境對于開發者是未知、多樣的,并且難以改變,所以優化代碼質量是提高代碼效率的主要途徑。
JS代碼中,循環是比較容易導致性能問題的因素。理解循環特性進而有針對性地進行優化也許會帶來不錯的性能提升。
for、while、do-while循環:
這三種循環本身的循環效率相差不多,所以只要根據適合的應用場景選擇即可。
以for循環為例:
復制代碼 代碼如下:
var aValues = ["a", "b", "c", "d"];
for(var i = 0; i < aValues.length; i += 1){
fDoSomethingA(aValues[i]);
fDoSomethingA(aValues[i]);
}
復制代碼 代碼如下:
var aValues = ["a", "b", "c", "d"], nLength = aValues.length;
for(var i = 0, sValue; i < nLength; i += 1){
sValue = aValues[i];
fDoSomethingA(sValue);
fDoSomethingB(sValue);
}
復制代碼 代碼如下:
var aValues = ["a", "b", "c", "d"], nLength = aValues.length;
for(var i = nLength, sValue; i -= 1;){
sValue = aValues[i];
fDoSomethingA(sValue);
fDoSomethingB(sValue);
}
復制代碼 代碼如下:
var aContact = ["N", "FN", "EMAIL;PREF", ...];
for(var i = aContact.length; i -= 1;){
fDoSomething(aContact[i]);
}
復制代碼 代碼如下:
for(var i = aValues.length; i -= 1){
fDoSomething(aValues[i]);
}
復制代碼 代碼如下:
fDoSomething(aValues[0]);
fDoSomething(aValues[1]);
fDoSomething(aValues[2]);
fDoSomething(aValues[3]);
...
...
fDoSomething(aValues[N-1]);
復制代碼 代碼如下:
var nLength = aContacts.length,
// 總輪數
nRounds = Math.floor( nLength / 8),
// 額外余量
nLeft = nLength % 8,
i = 0;
// 先處理余量
if(nLeft){
do{
fFormat(aContacts[i ++]);
}while(-- nLeft)
}
// 每輪執行8次格式化
if(nRounds){
do{
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
fFormat(aContacts[i ++]);
}while(-- nRounds)
}
新聞熱點
疑難解答
圖片精選