“This is the 26th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Before ECMAScript 6, implementing “key/value” storage in JavaScript could be done easily and efficiently using Object, that is, using Object properties as keys and using properties to reference values. But this implementation is not without its problems, and the TC39 committee has defined a specification specifically for “key/value” storage.

A new feature of ECMAScript 6, Map is a new collection type that brings true key/value storage to the language. Most of Map’s features can be implemented with the Object type, but there are some subtle differences. Which one to use in specific practice is still worth careful screening

Basic Usage API

Const m = new Map();

There are two ways to initialize instances of a Map: 1. Initialize a Map using a nested array 2. Initialize the map using a custom iterator

// Initialize the map with a nested array
const m1 = new Map([["key1"."val1"],
["key2"."val2"],
["key3"."val3"]]); alert(m1.size);/ / 3

// Initializes the map using a custom iterator
const m2 = new Map({[Symbol.iterator]: function* () {
yield ["key1"."val1"];
yield ["key2"."val2"];
yield ["key3"."val3"]; }}); alert(m2.size);/ / 3
Copy the code

After initialization, you can add key/value pairs using the set() method. In addition, you can use get() and has() for queries, the size attribute to get the number of key/value pairs in the map, and delete() and clear() to delete values.

const m = new Map(a); alert(m.has("firstName")); // false
alert(m.get("firstName")); // undefined
alert(m.size); / / 0

m.set("firstName"."Matt")
 .set("lastName"."Frisbie");

alert(m.has("firstName")); // true
alert(m.get("firstName")); // Matt
alert(m.size); / / 2

m.delete("firstName"); // Delete only one key/value pair
alert(m.has("firstName")); // false
alert(m.has("lastName")); // true
alert(m.size); / / 1

m.clear(); // Clears all key/value pairs in this mapping instance

alert(m.has("firstName")); // false
alert(m.has("lastName")); // false
alert(m.size); / / 0
Copy the code

The set() method returns an instance of the mapping, so you can concatenate multiple operations, including initialization declarations

const m = new Map().set("key1"."val1");
m.set("key2"."val2")
 .set("key3"."val3");

alert(m.size); / / 3
Copy the code

Unlike Object, which can only use numeric values, strings, or symbols as keys, Maps can use any JavaScript data type as keys

Sequence and iteration

One major difference with Object is that Map instances maintain the insertion order of key-value pairs, so you can iterate based on the insertion order.

A mapping instance can provide an Iterator that generates an array of [keys, values] in insert order. This iterator can be obtained through the entries() method (or the symbol.iterator property, which references entries()) :

const m = new Map([["key1"."val1"],
["key2"."val2"],
["key3"."val3"]]); alert(m.entries === m[Symbol.iterator]); // true

for (let pair of m.entries()) {
alert(pair);
}
// [key1,val1]
// [key2,val2]
// [key3,val3]

for (let pair of m[Symbol.iterator]()) {
alert(pair);
}
// [key1,val1]
// [key2,val2]
// [key3,val3]

Copy the code

Keys (), values(), and entries() can all be used to return iterate objects

let hd = new Map([["xiaoyiya"."Little too."], ["qdxx"."Front-end learning"]]);
console.log(hd.keys()); //MapIterator {"xiaoyiya", "qdxx"}
console.log(hd.values()); //MapIterator {" small ", "front-end learning "}
console.log(hd.entries()); / / MapIterator {" xiaoyiya "= >" little also ah ", "QDXX" = > "front-end study"}
Copy the code

Keys /values can be used to iterate over keys and values

let hd = new Map([["xiaoyiya"."Little too."], ["qdxx"."Front-end learning"]]);
for (const key of hd.keys()) {
  console.log(key);
}
for (const value of hd.values()) {
  console.log(value);
}

Copy the code

For /of traversal, traversing Map sequentially is equivalent to using entries()

let hd = new Map([["xiaoyiya"."Little too."], ["qdxx"."Front-end learning"]]);
for (const [key, value] of hd) {
  console.log(`${key}= >${value}`);
}
Copy the code

Use forEach to traverse the operation

let hd = new Map([["xiaoyiya"."Little too."], ["qdxx"."Front-end learning"]]);
hd.forEach((value, key) = > {
  console.log(`${key}= >${value}`);
});
Copy the code

Comparison of Object and Map selections

For most Web development tasks, the choice between Object and Map is a matter of personal preference, with little impact. However, for developers who care about memory and performance, there are significant differences between objects and maps.

  1. Memory footprint

The engineering-level implementation of Object and Map varies significantly between browsers, but the amount of memory used to store a single key/value pair increases linearly with the number of keys. Adding or removing key/value pairs in batches depends on the engineering implementation of the type of memory allocated by each browser. This varies by browser, but given a fixed size of memory, Map can store approximately 50% more key/value pairs than Object.

  1. Insert performance

Inserting new key/value pairs into Object and Map costs roughly the same, although inserting a Map is generally a little faster in all browsers. For both types, the insertion speed does not increase linearly with the number of key/value pairs. If the code involves a lot of inserts, then clearly the Map performs better.

  1. To find the speed

Unlike insertion, finding key/value pairs from large objects and maps has minimal performance differences, but objects can sometimes be faster if only a few key/value pairs are included. In cases where objects are used as arrays (such as contiguous integers as attributes), the browser engine can be optimized to use a more efficient layout in memory. This is not possible for Map. For both types, lookup speed does not increase linearly with the number of key/value pairs. If your code involves a lot of lookups, it might be better to choose Object in some cases.

  1. Delete the performance

The performance of using delete to remove the Object property has long been criticized, and still is in many browsers. For this reason, there are some pseudo-deletions of object attributes, including setting the attribute value to undefined or NULL. But all too often, this is a nasty or inappropriate compromise. For most browser engines, Map’s delete() operation is faster than insert and lookup. If your code involves a lot of deletions, you should definitely choose Map.