Which one should you choose, Map or Object?

Summarize

If you can use Map, you can use Map. Object has no obvious advantage over Map.

  1. The amount of data is large, and Map is used for frequent writing.
  2. There is a requirement for the write order to use Map

analyze

Object

V8 has optimization methods for the processing of Objects;

When there are few object properties or the key is a numeric type, fast properties are used, and fast properties are stored in a linear structure.

When there are more attributes, in order to ensure the efficiency of adding and deleting, slow attributes will be used, and the content of attributes will be stored in the form of key-value pairs.

Map

The storage structure of Map is hashMap

Compared

  • The key of Object can only be a number, string, or Symbol; the key of Map can be of any type;
  • Map is an iterative object; Object cannot be iterated;
  • Map will record the writing order; Object will serialize the key and sort it according to the dictionary;
  • Map has various built-in operation functions; Object does not;

Comparison of read and write operations

write

// 先定义一个数量上限\
const up = 9999

var mt1 = performance.now()
var map = new Map()
for(var i = 0; i < up; i++) {
  map.set(`f${i}`, {a: i, children: { a: i }})
}

console.log(`   Map: `, performance.now() - mt1)

var ot1 = performance.now()
var obj = {}

for (var i = 0; i < up; i++) {
  obj[`f${i}`] = {b: i, children: {a: i}}
}

console.log('Object: ', performance.now() - ot1)
复制代码

When I set the value of up 499999 to , the writing speed of Object starts to stabilize and takes longer than that of Map. When it is smaller than 499999the object speed, the ratio is higher, but the difference is not obvious.

read

// 访问
for (var i = 0; i < up; i++) {
  map.get(`f${i}`)
}
复制代码

In terms of reading speed,  159999 when the value of up is set, the reading speed of Object will be stable and slower than that of Map.

delete

// 删除
for(var i = 0; i < up; i++) {
  map.delete(`f${i}`)
}
复制代码

In deletion, I set the value of up to  199999 be stable and slower than Map's deletion.

Therefore, in terms of performance, when the speed of adding, deleting, and reading is very small, the performance of Object may be slightly better, or even not obvious. When the number is very large, Map will perform better than Object.

Reference link: The truth of the Map application scenario is...

Guess you like

Origin juejin.im/post/7083827091875037215