循環展開是一種程序變換,經過增長每次迭代計算的元素的數量,減小循環的迭代次數。git
用代碼來講明就是將github
for (i = 0; i < len; i++) {
sum += arry[i]
}
複製代碼
替換爲chrome
for (i = 0; i < len; i += 2) {
newSum += arry[i] + arry[i + 1]
}
複製代碼
循環展開對於算術運算來講,優化的做用是很大的。我分別對整數運算和浮點數運算做了屢次測試,得出表格以下:瀏覽器
操做 | 整數 | 整數(優化後) | 浮點數 | 浮點數(優化後) |
---|---|---|---|---|
+ | 360 | 163 | 354 | 164 |
- | 379 | 167 | 341 | 177 |
* | 350 | 160 | 364 | 163 |
/ | 118 | 57 | 152 | 63 |
運算是用了1千萬個數,取值是運行十次測試得出的平均數。附上加法測試的代碼bash
const arry = []
let num = 10000000
while (num) {
arry.push(num)
num--
}
let sum = 0
let last = new Date()
let i
let len = arry.length
for (i = 0; i < len; i++) {
sum += arry[i]
}
let now = new Date()
console.log(now - last)
let newSum = 0
last = new Date()
for (i = 0; i < len; i += 2) {
newSum += arry[i] + arry[i + 1]
}
now = new Date()
console.log(now - last)
console.log(sum, newSum)
複製代碼