conclusion

Use Map whenever possible. Object has no obvious advantage over Map

  1. Map is used for frequent data writing
  2. Map is required for write order

Analysis of the

Object

V8 has optimization means for Object processing;

When the object has few attributes or the key is of numeric type, fast attributes are used. Fast attributes are stored in linear structures.

When the number of attributes increases, in order to ensure the efficiency of adding and deleting attributes, slow attributes and key-value pairs are used to store attribute contents.

Map

The Map storage structure is a hashMap

contrast

  • The key of an Object can only be a number, string, or Symbol. Map keys can be of any type;
  • Map is an iterator; Object cannot be iterated;
  • Map records the write order; Object serializes keys and sorts them according to the dictionary;
  • Map has various built-in manipulation functions; The Object is not;

Comparison of read and write operations

write

// Define a quantity upper bound \
const up = 9999

var mt1 = performance.now()
var map = new Map(a)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)
Copy the code

When I set the value of up to 499999, the write speed of Object began to be stable and longer than that of Map. Less than 499999, the proportion of Object fast is higher, but the difference is not significant.

read

/ / access
for (var i = 0; i < up; i++) {
  map.get(`f${i}`)}Copy the code

In terms of read speed, when the value of up is 159999, the read speed of Object is stably slower than that of Map.

delete

/ / delete
for(var i = 0; i < up; i++) {
  map.delete(`f${i}`)}Copy the code

In terms of deletion, I set the value of up to 199999 so that the deletion time of Object is stable and slower than that of Map.

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

The truth of the Map application scenario is…