部分摘自《代碼大全》優化
1.讓運行最快和較大機率爲真多判斷首先被執行code
適用於if/else和case語句it
2.用查詢表代替複雜的表達式class
若是有複雜的輸入,先將結果計算好放在一張表裏file
3.避免在循環中重複判斷,循環
4.設置哨兵值並行
bool found = false; i = 0; while(!found && i < cnt) { if (item[i++] == value) { found = true; break; } } // 優化後 item[cnt] = value; while( item[i] != value) { i++; } if(i < cnt) found = true;
5.循環展開im
nt amount = 0; for(int i = 0; i < len; i++) { amount += a[i]; } // 優化後 int i = 0; while(i < len - 3) //注意不能超過len,最後len%4個要處理 { amount += (a[i + a[i + 1] + a[i + 2] + a[i + 3] ) ; // amount += a[i + 1]; 依賴上一條語句的執行結果,只能順序執行,不能利用cpu的並行計算 i += 4; } while(i < len) { amount += a[i]; i++; }
6.profile driven optimizecpu
舉個例子:查詢
a = b * 50;
若是b大部分狀況都等於10,能夠優化以下:
a = 50; if (b != 10) { a = b * 10; }