import-html-entry
import-html-entry copied to clipboard
feat(utils.js): replace for-in with Object.keys in noteGlobalProps()
实现方案
- 使用 for-in
for (let p in window) {
if (!shouldSkipProperty(window, p)) continue
if (!firstGlobalProp)
firstGlobalProp = p
else if (!secondGlobalProp)
secondGlobalProp = p
lastGlobalProp = p
}
- 使用 Object.keys
Object
.keys(window)
.forEach((p) => {
if (!shouldSkipProperty(window, p)) return
if (!firstGlobalProp)
firstGlobalProp = p
else if (!secondGlobalProp)
secondGlobalProp = p
lastGlobalProp = p
})
- 使用 Object.keys获取keys,然后基于传统 for-loop 遍历
let p
for(let i = 0, keys = Object.keys(window), len = keys.length; i < len; i++) {
p = keys[i]
if (!shouldSkipProperty(window, p)) continue
if (!firstGlobalProp)
firstGlobalProp = p
else if (!secondGlobalProp)
secondGlobalProp = p
lastGlobalProp = p
}
用例:
3种实现方案分别对 window 进行1000遍历,并执行 firstGlobalProp、secondGlobalProp、lastGlobalProp 的赋值操作。
结果

- BenchMark用例详见:https://codepen.io/lqy455949477/pen/oNLzJBK
分析:
- 范围减小:for-in会遍历对象的属性和在 prototype 上的方法,基于 Chrome 86来看,总共遍历了237个属性(或方法)。而 Object.keys 仅遍历233个属性。
- global.hasOwnProperty()的运行效率:在遍历到 prototype 方法时,该API的性能会急剧下降。
遗留问题:
- 方案3的性能相比方案2理论上会有一定的提升,因为没有通过 forEach 去多次调用某个函数。但实际测试下来,没有明显提升,甚至某些情况下性能会低于方案2,可能需要更多测试来验证。
Codecov Report
Merging #58 into master will not change coverage. The diff coverage is
0.00%.
@@ Coverage Diff @@
## master #58 +/- ##
=======================================
Coverage 52.91% 52.91%
=======================================
Files 3 3
Lines 257 257
Branches 82 82
=======================================
Hits 136 136
Misses 90 90
Partials 31 31
| Impacted Files | Coverage Δ | |
|---|---|---|
| src/utils.js | 26.41% <0.00%> (ø) |
Continue to review full report at Codecov.
Legend - Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing dataPowered by Codecov. Last update fb9d120...27023b1. Read the comment docs.