Home > Web Front-end > JS Tutorial > body text

Comparison of JavaScript object iteration methods and performance

hzc
Release: 2020-06-10 16:51:46
forward
2871 people have browsed it

Object.entries


Returns all enumerable key-value pairs of the object, and will not track the key# on the prototype chain. ##

let obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}
Object.entries(obj).forEach(entry => {
  let key = entry[0]
  let value = entry[1]
  // entry 会是这样 ["key1", "value1"]
})
Copy after login

Object.keys


Returns all enumerable keys of the object

let obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}
Object.keys(obj).forEach(key => {
  let value = obj[key]
})
Copy after login

Object.values


Return all enumerable values ​​of the object

let obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}
Object.values(obj).forEach(value => {
  // 只能使用 value
})
Copy after login

for…in loop


Iterate over the enumerable properties, Will look for it along the prototype chain

let obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}
for (const key in obj) {
  let value = obj[key]
  if (obj.hasOwnProperty(key)) {
    // 本身的
  } else {
    // 来自原型链的
  }
}
Copy after login

Object.getOwnPropertyNames


Returns all keys of the object (including non-enumerable) keys (the original text says it will look for the prototype chain is wrong)

let obj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
}
Object.getOwnPropertyNames(obj).forEach(key => {
  let value = obj[key]
})
Copy after login

Performance comparison


The following code uses the above methods to traverse objects with 1,000,000 attributes and loop 10 times

const { PerformanceObserver, performance } = require('perf_hooks')

let objectSize = 1000000
let iterations = 10

console.log(
  'Starting performance test with %d object size and %d iterations',
  objectSize,
  iterations
)

let values = {
  ENTRIES: 0,
  KEYS: 0,
  VALUES: 0,
  FORIN: 0,
  GETOWP: 0,
}

const obs = new PerformanceObserver(items => {
  let entry = items.getEntries()[0]
  console.log(entry.name, entry.duration)
  values[entry.name] += entry.duration
  performance.clearMarks()
})
obs.observe({ entryTypes: ['measure'] })

function generateObject() {
  let obj = {}
  for (let i = 0; i < objectSize; i++) {
    obj['key' + Math.random()] = 'val' + Math.random()
  }
  return obj
}

for (let i = 0; i < iterations; i++) {
  let obj = generateObject()

  //Object.entries
  performance.mark('A')
  Object.entries(obj).forEach(entry => {
    let key = entry[0]
    let value = entry[1]
  })
  performance.mark('B')
  performance.measure('ENTRIES', 'A', 'B')

  //Object.Keys
  performance.mark('A')
  Object.keys(obj).forEach(key => {
    let value = obj[key]
  })
  performance.mark('B')
  performance.measure('KEYS', 'A', 'B')

  //Object.Values
  performance.mark('A')
  Object.values(obj).forEach(value => {})
  performance.mark('B')
  performance.measure('VALUES', 'A', 'B')

  //For In
  performance.mark('A')
  for (const key in obj) {
    let value = obj[key]
  }
  performance.mark('B')
  performance.measure('FORIN', 'A', 'B')

  //Object.getOwnPropertyNames
  performance.mark('A')
  Object.getOwnPropertyNames(obj).forEach(key => {
    let value = obj[key]
  })
  performance.mark('B')
  performance.measure('GETOWP', 'A', 'B')
}

console.log(
  Object.entries(values).sort((a, b) => {
    return a[1] - b[1]
  })
)
Copy after login

The following results were run by myself. Sequential means using index directly when assigning values. Random means inserting random numbers into key-value pairs. The performance ranking is the same as the author's, because node. Both js and chrome are V8, so this should also represent the performance ranking on the browser.

// 顺序
;[
  ['FORIN', 4677.321499],
  ['KEYS', 4812.776572],
  ['GETOWP', 8610.906197],
  ['VALUES', 9914.674390999999],
  ['ENTRIES', 19338.083694],
]

// 随机
;[
  ['KEYS', 4502.579589],
  ['FORIN', 4678.013548000001],
  ['GETOWP', 8880.325031999999],
  ['VALUES', 10104.106962],
  ['ENTRIES', 17089.637588999998],
]
Copy after login

I heard before that the engine will guess the next value to make it run faster. Looking at the data, it doesn’t seem to have much impact.

It can be regarded as a bit of useful information. Come to the original text and applaud the author.

Recommended tutorial: "

JS Tutorial"

The above is the detailed content of Comparison of JavaScript object iteration methods and performance. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!