先看两段代码
优化前
showNetMetric () {
let isShowNetMetric = false
if (this.v_networkMetrics && this.v_networkMetrics.length) {
this.v_networkMetrics.forEach(item => {
let justConditon = this.valueData(item.value)
justConditon.forEach(_item => {
if (_item && _item.length) {
_item.forEach(i => {
if (this.judgeNormalData(i)) {
isShowNetMetric = true
}
})
} else {
if (this.judgeNormalData(_item)) {
isShowNetMetric = true
}
}
})
})
}
return isShowNetMetric
},
第一次优化后
showNetMetric () {
let isShowNetMetric = false
if (this.v_networkMetrics && this.v_networkMetrics.length) {
for (let i = 0; i < this.v_networkMetrics.length; i++) {
let justConditon = this.valueData(this.v_networkMetrics[i].value)
for (let j = 0; j < justConditon.length; j++) {
if (justConditon[j] && justConditon[j].length) {
for (let k = 0; k < justConditon[j].length; k++) {
if (this.judgeNormalData(justConditon[j][k])) {
isShowNetMetric = true
break
}
}
} else {
if (this.judgeNormalData(justConditon[j])) {
isShowNetMetric = true
break
}
}
}
}
}
return isShowNetMetric
},
第三次优化:
if (this.v_networkMetrics && this.v_networkMetrics.length) {
for (let i = 0; i < this.v_networkMetrics.length; i++) {
let justConditon = this.valueData(this.v_networkMetrics[i].value)
for (let j = 0; j < justConditon.length; j++) {
if (justConditon[j] && justConditon[j].length) {
for (let k = 0; k < justConditon[j].length; k++) {
if (this.judgeNormalData(justConditon[j][k])) {
return true
}
}
} else {
if (this.judgeNormalData(justConditon[j])) {
return true
}
}
}
}
}
return false
解释:都是循环数组,forEach没有break,它会一直一直循环下去。即便已经满足了相关条件,它还是会循环。性能很差。
第二次优化:
使用for循环,当满足条件,循环结束。性能还是不好,原因是:这里的嵌套太深了,break 只是当前的循环结束,外面的循环仍在继续。
然后就有了第三次优化了。