Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils.js): replace for-in with Object.keys in noteGlobalProps() #58

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

feat(utils.js): replace for-in with Object.keys in noteGlobalProps() #58

wants to merge 1 commit into from

Conversation

attax1994
Copy link

@attax1994 attax1994 commented Oct 21, 2020

实现方案

  1. 使用 for-in
for (let p in window) {
  if (!shouldSkipProperty(window, p)) continue
  if (!firstGlobalProp)
    firstGlobalProp = p
  else if (!secondGlobalProp)
    secondGlobalProp = p
  lastGlobalProp = p
}
  1. 使用 Object.keys
Object
  .keys(window)
  .forEach((p) => {
    if (!shouldSkipProperty(window, p)) return
    if (!firstGlobalProp)
      firstGlobalProp = p
    else if (!secondGlobalProp)
      secondGlobalProp = p
    lastGlobalProp = p
  })
  1. 使用 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 的赋值操作。

结果

image

分析:

  1. 范围减小:for-in会遍历对象的属性和在 prototype 上的方法,基于 Chrome 86来看,总共遍历了237个属性(或方法)。而 Object.keys 仅遍历233个属性。
  2. global.hasOwnProperty()的运行效率:在遍历到 prototype 方法时,该API的性能会急剧下降。

遗留问题:

  1. 方案3的性能相比方案2理论上会有一定的提升,因为没有通过 forEach 去多次调用某个函数。但实际测试下来,没有明显提升,甚至某些情况下性能会低于方案2,可能需要更多测试来验证。

@codecov-io
Copy link

Codecov Report

Merging #58 into master will not change coverage.
The diff coverage is 0.00%.

Impacted file tree graph

@@           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 data
Powered by Codecov. Last update fb9d120...27023b1. Read the comment docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants