Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Previously, we learned about the Map class. A Map object represents a group of values called keys, and each key is associated with a value to form a mapping relationship. Today we will learn about another (weak mapping) class, WeakMap
JavaScript WeakMap
In JavaScript, you’ll see a lot of things that have a key that’s a string, but sometimes when you need an object or an array,
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(new WeakMap()) // '[object WeakMap]'
Copy the code
Can see the use of the Object. The prototype. ToString. Call () method for Object {} and new WeakMap judging (), results showed that both is different
At this time, there are two data structures Map and WeakMap. Today, I will mainly study WeakMap.
Review the Map class (Mapping)
Map is used to create a mapping object to store key name/value mappings
let map = new Map(a)// New creates a mapping object for key/value mapping
Copy the code
WeakMap class (weak mapping)
WeakMap Weak mapping is mainly used to associate values with objects without causing memory leaks. Here’s the explanation:
WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs. However, WeakMap only accepts objects as key names (except null) and does not accept other types of values as key names. Moreover, the object to which the key name of WeakMap points is not included in the garbage collection mechanism.
When Vue3 source code, we will see the keyword WeakMap
// First we need to set up two caches
let toProxy = new WeakMap(a)// Query the data after the response based on the original data
let toRaw = new WeakMap(a)// Query the raw data based on the response data
Copy the code
The cache is then queried when reactive data is written, reducing unnecessary performance costs
Here, target is the object to be responsive, and WeakMap is used for data caching
function reactive(target) {
// Query the cache
let observed = toProxy.get(target)
if (observed) {
return observed
}
if (toRaw.get(target)) {
return target
}
/ / response type
observed = new Proxy(target, baseHandler)
// Set the cache
toProxy.set(target, observed)
toRaw.set(observed, target)
return observed
}
Copy the code