In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use WeakMap as a cache area in Vue3". In daily operation, I believe that many people have doubts about how to use WeakMap as a cache area in Vue3. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use WeakMap as a cache area in Vue3". Next, please follow the editor to study!
In the process of reading the Vue 3 responsive principle part of the code, you can see that when it is doing responsive processing, it creates a "cache area" for each object using WeakMap, as follows:
/ / pay attention to the following code! Const reactiveMap = new WeakMap (); / / the core hijacking method handles the logic of get and set const mutableHandlers = {get, set} function reactive (target: object) {return createReactiveObject (target, mutableHandlers, reactiveMap) } / * @ description create responsive object * @ param {Object} target target object that needs to be proxied * @ param {Function} baseHandlers for different processing functions corresponding to each method * @ param {Object} proxyMap WeakMap object * / function createReactiveObject (target, baseHandlers, proxyMap) {/ / detect whether target is an object, not returned directly Do not proxy if (! isObject (target)) {return target} const existsProxy = proxyMap.get (target) / / if the object has already been proxied, return directly without repeating the proxy if (existsProxy) {return existsProxy} / / create a proxy object const proxy = new Proxy (target,baseHandlers); / / cache to avoid duplicate proxies, that is, avoid proxyMap.set (target,proxy) in the case of reactive (reactive (Object)); return proxy}
As you can see from the above code, the purpose of the WeakMap cache is to prevent objects from being proxied repeatedly.
Why does Vue 3 use WeakMap to cache proxy objects? Why not use other ways to cache, such as Map?
What is WeakMap?
A WeakMap object is a collection of key-value pairs where keys are weakly referenced. The key must be an object, and the value can be arbitrary.
Syntax new WeakMap ([iterable])
An Iterable is an array (binary array) or other iterated object whose elements are key-value pairs. Each key-value pair is added to the new WeakMap.
Method
There are four methods for WeakMap: get, set, has, and delete. Let's take a look at its general usage:
Const wm1 = new WeakMap (), wm2 = new WeakMap (), wm3 = new WeakMap (); const o1 = {}, O2 = function () {}, o3 = window;wm1.set (o1,37); wm1.set (O2, "azerty"); wm2.set (o1, O2); / / value can be any value, including an object or a function wm2.set (o3, undefined); wm2.set (wm1, wm2) / / the key and value can be any object, or even another WeakMap object wm1.get (O2); / / "azerty" wm2.get (O2); / / undefined,wm2 does not have the key O2 wm2.get (o3); / / undefined, the value is undefinedwm1.has (O2); / / truewm2.has (O2); / / falsewm2.has (o3); / / true (even if the value is undefined) wm3.set (o1, 37); wm3.get (o1) / / 37wm1.has (o1); / / truewm1.delete (o1); wm1.has (o1); / / Why should false use WeakMap instead of Map
In JavaScript, map API can be implemented through four API methods that share two arrays (one store key and one store value). This adds both the key and the value to the end of both arrays when setting a value for this map. So that the indexes of the key and the value correspond to each other in the two arrays. When fetching values from this map, you need to iterate through all the keys, and then use the index to retrieve the corresponding values from the array where the values are stored.
However, such an implementation has two big disadvantages: first, the assignment and search operations are both O (n) time complexity (n is the number of key-value pairs), because both operations need to traverse the entire array to match.
Another disadvantage is that it can lead to memory leaks because the array references each key and value all the time. This reference makes it impossible for the garbage collection algorithm to recycle them, even if no other references exist.
Let jser = {name: "dachui"}; let array = [jser]; jser = null; / / override reference
In the above code, we put an object into an array, so as long as the array exists, then the object exists, even if there are no other references to the object.
Let jser = {name: "dachui"}; let map = new Map (); map.set (jser, ""); jser = null; / / override reference
Similarly, if we use an object as the key to a regular Map, then when Map exists, the object will also exist. It takes up memory and is not reclaimed by the garbage collection mechanism.
By contrast, the native WeakMap holds a weak reference to each key object, which means that garbage collection works correctly when no other references exist.
Because of such weak references, the key of WeakMap is not enumerable (there is no way to give all the key). If key is enumerable, its list will be affected by the garbage collection mechanism, resulting in uncertain results. Therefore, if you want a list of key values for this type of object, you should use Map.
To sum up, we can draw the following conclusion: the object pointed to by the key of WeakMap is not included in the garbage collection mechanism.
So, if you want to add data to an object without interfering with the garbage collection mechanism, you can use WeakMap.
As you can see here, Vue 3 uses WeakMap as a buffer in order to garbage collect data that is no longer in use.
What is a weak reference?
Wikipedia gives the answer to "weak quotes":
In computer programming, a weak reference as opposed to a strong reference is a reference that cannot be guaranteed that the object it references will not be reclaimed by the garbage collector. An object that is referenced only by a weak reference is considered inaccessible (or weakly accessible) and may therefore be recycled at any time. Why are there weak references?
So why are there weak references? What other problems can weak references solve besides the above problems? To answer these questions, we first need to understand how the V8 engine does garbage collection.
For JSer, memory management is automatic and invisible, all thanks to the V8 engine silently helping us find unused memory and clean it up.
So what happens when we no longer need something, and how does the V8 engine find and clean it up?
Nowadays, there are two methods for garbage collection commonly used by major browsers, one is "reference counting", and the other is "tag cleanup". Let's take a look at this:
Mark clear
Tag cleanup, called mark-and-sweep, determines whether an object is alive based on reachability and periodically performs the following "garbage collection" steps:
The garbage collector finds all the roots and marks (remember) them.
Then it traverses and marks all references from them. All traversed objects are remembered to avoid traversing to the same object again in the future.
…… Do this until all reachable (from the root) references are accessed.
Objects that are not marked will be deleted.
We can also think of this process as a huge paint bucket overflowing from the root, which flows through all references and marks all reachable objects, and then removes the untagged.
Reference count
The most basic form of reference counting is to associate each managed object with a reference counter that records the number of times the object is currently referenced. Each time a new reference is created to point to the object, the counter is increased by 1, and the counter is subtracted by 1 whenever the reference to the object expires. When the value of the counter drops to 0, the object is considered dead.
Difference
The biggest difference between reference counting and memory management based on "accessibility" tag cleanup is that the former requires only local information, while the latter requires global information.
In the reference count, each counter only records the local information of its corresponding object-the number of references, and does not (and does not need) the life and death information of a global object graph.
Since only local information is maintained, dead objects can be identified and released without scanning the global object graph. But also because of the lack of global object graph information, it is impossible to deal with circular references.
Therefore, more advanced reference counting implementations introduce the concept of weak references to break some known circular references.
WeakMap application storage DOM node
The typical case of WeakMap application is to use the DOM node as the key name. Here is an example.
Const myWeakmap = newWeakMap (); myWeakmap.set (document.getElementById ('logo'), {timesClicked: 0},); document.getElementById (' logo'). AddEventListener ('click', () = > {const logoData = myWeakmap.get (document.getElementById (' logo')); logoData.timesClicked++;}, false)
In the above code, document.getElementById ('logo') is a DOM node that updates the status whenever a click event occurs. We put this state as a value in WeakMap, and the corresponding key is the node object. Once the DOM node is deleted, the state automatically disappears and there is no risk of a memory leak.
Data caching
The answer lies in the riddle, and the question we asked at the beginning of the article is the answer here. Vue 3 uses WeakMap as the "cache" of responsive objects when implementing the responsive principle.
The usage of this point is also very simple, WeakMap can be used when we need to associate objects and data, such as storing certain properties or storing some calculated values based on the object without modifying the original object, but do not want to manage these memory problems manually.
Deploy private properties in the class
Another use of WeakMap is to deploy private properties in a class.
It is worth mentioning that the private private attribute principle that has been implemented in TypeScript is the use of WeakMap.
Private attributes should not be accessible by the outside world and cannot be shared by multiple instances. It is unreliable to use underscores to mark private attributes and methods to a certain extent in JavaScript.
Let's do this in three ways:
Version 1: closures
Const testFn = (function () {let data; class Test {constructor (val) {data = val} getData () {return data;}} return Test;}) (); let test1 = new testFn (3); let test2 = new testFn (4); console.log (test1.getData ()); / / 4console.log (test2.getData ()); / / 4
You can see that the final output is 4, and multiple instances share private attributes, so the version does not match.
Version 2: Symbol
Const testFn = (function () {let data = Symbol ('data') class Test {constructor (val) {this [data] = val} getData () {return this [data]}} return Test;}) (); let test1 = new testFn (3); let test2 = new testFn (4); console.log (test1.getData ()); / / 3console.log (test2.getData ()) / 4console.log (Test1 [Object.getOwnPropertySymbols (test1) [0]]); / / 3console.log (Test2 [Object.getOwnPropertySymbols (test2) [0]]); / / 4
Although using Symbol to implement and output 3 and 4 correctly, we found that we can get private properties directly without using the getData method, so this method does not meet our requirements.
Version 3: WeakMap
Const testFn = (function () {let data = new WeakMap () class Test {constructor (val) {data.set (this, val)} getData () {return data.get (this)}} return Test;}) (); let test1 = new testFn (3); let test2 = new testFn (4); console.log (test1.getData ()); / / 3console.log (test2.getData ()) / / 4 at this point, the study on "how to use WeakMap as a cache in Vue3" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.