Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript weak mapping and weak collection knowledge

Detailed explanation of JavaScript weak mapping and weak collection knowledge

WBOY
WBOYforward
2022-06-20 11:21:382004browse

This article brings you relevant knowledge about javascript, which mainly introduces issues related to weak mapping and weak collections. Let’s take a look at it together. I hope it will be helpful to everyone.

Detailed explanation of JavaScript weak mapping and weak collection knowledge

[Related recommendations: javascript video tutorial, web front-end]

Simply speaking, if a If a variable or object is "unreachable", then there is no need for the variable or object to continue to be stored in memory and should be recycled.

For example:

let xiaoming = {name:'xiaoming'}//创建一个对象,并用变量xiaoming引用

xiaoming = null	//将变量xiaoming置空,从而使对象{name:'xiaoming'}不可达

//{name:'xiaoming'}对象被回收

If an object is referenced by an array and other objects, as long as it refers to the array and the object exists in the array, then the object is considered reachable.

Objects in the array:

let xiaoming = {name:'xiaoming'}
let arr = [xiaoming]
xiaoming = null //将变量xiaoming置空
//对象{name:'xiaoming'}由于存在于数组中,并不会被释放

Similarly, if we use an object as the key of Map, if Map exists, then the object It will not be recycled by the engine. Key objects in

Map:

let xiaoming = {name:'xiaoming'}
let map = new Map()
map.set(xiaoming,'a boy')
xiaoming = null //将变量xiaoming置空
//对象{name:'xiaoming'}由于是map的键,并不会被释放

WeapMap is essentially the same as Map in the processing of releasing key objects The difference is, simply put, WeapMap will not prevent garbage collection because the object is used as a key. The difference between

WeakMap

WeakMap and Map can be divided into three aspects:

  1. WeakMap Only objects can be used as keys
let weakMap = new WeakMap()
let obj = {name:'obj'}
weakMap.set(obj,'obj as the key')
weakMap.set('str','str as the key')//报错

The code execution results are as follows:

Detailed explanation of JavaScript weak mapping and weak collection knowledge

is visible when we use strings as When key is used, the program cannot execute normally.

  1. Does not prevent the engine from recycling keys (objects)

That is, if an object has no other references except the reference to WeakMap , then the object will be recycled by the system.

For example:

let weakMap = new WeakMap()
let obj = {name:'obj'}
weakMap.set(obj,'obj as the key')
obj = null	//将变量obj置空
//此时,对象{name:'obj'}就会被回收
  1. WeakMapSupported methods are limited
  • ##WeakMap Iteration is not supported
  • WeakMapNot supportedkeys()
  • WeakMapNot supportedvalues()
  • WeakMapDoes not support entires()
So, we have no way to get all key-value pairs.

WeakMapYou can only use the following methods:

  • weakMap.get(key)Get the key-value pair
  • weakMap.set(key,val)Set key-value pair
  • weakMap.delete(key)Delete key-value pair
  • weakMap .has(key)Determine whether it exists
The reason why we need to restrict the data access method of

WeakMap is because of the timing of JavaScript engine releasing the object It is impossible to determine.

When an object loses all references, the

JavaScript engine may release the space occupied by the object immediately, or it may wait a while.

So, at a certain moment, the number of elements in

WeakMap cannot be determined. (Just imagine, if we traverse the elements of WeakMap after an object loses all references, we may get different results.)

WeakMap use case

# The application scenario of ##WeakMap

is usually to store data that "belongs" to an object. When the object does not exist, the data that "belongs" to the object should also be released accordingly. There is a historical story that is very suitable for using WeakMap`: "The cunning rabbit dies, and the lackeys are cooked; the birds are gone, and the good bow is hidden."

If we use

JavaScript

code to describe this story, we should use WeakMap:<pre class="brush:php;toolbar:false">let weakMap = new WeakMap() let rabbit = {name:'rabbit'}   //狡兔 let runDog  = {name:'runDog'} //走狗 let flyBird = {name:'flyBird'} //飞鸟 let goodBow = {name:'goodBow'} //良弓 weakMap.set(rabbit,runDog) weakMap.set(flyBird,goodBow) rabbit = null //狡兔死 flyBird = null //飞鸟尽 //随即,走狗和良弓都会被释放,也可能不是立刻就释放 //这个故事告诉我们,当走狗没有啥好下场,可能不是立刻就被 //弄死了,但是迟早要弄死</pre>WeakSet

and

Compared with Set

, WeakSet has the following differences:

    WeakSet
  1. can only add object elements
  2. WeakSet
  3. Does not prevent the system from recycling elements
  4. WeakSet
  5. Supports add(), has(), delete()
  6. WeakSet
  7. does not support the size attribute and keys() method
  8. we can use
WeakMap

to verify some existence information, or verify "yes/no" status, for example, we can use WeakMap to determine whether the user is online: <pre class="brush:php;toolbar:false">let onlineUser = new WeakMap() let zhangSan = {name:'张三'} let liSi = {name:'李四'} let wangEr = {name:'王二'} let maZi = {name:'麻子'} function login(user){     ... ...     onlineUser.add(user) } //判断用户是否在线 function isOnline(user){     return onlineUser.has(user) }</pre>

The limitation of WeakMap

and WeakSet is that they cannot iterate and obtain all elements at once, which does not affect their important role in very critical places. <h2>Summary</h2> <ol> <li> <code>WeakMap can only use objects as keys. When all external references to the keys are lost (there are no other variable references except WeakMap key object), WeakMap will not prevent the engine from recycling key values. Once recycled, the elements corresponding to WeakMap no longer exist.

  • WeakSet can only store objects. Once the object element loses all external references (except WeakSet, no other variables refer to the element object), WeakSet Will not prevent the engine from recycling elements. Once recycled, the corresponding elements in WeakSet disappear.
  • Their common advantage is that they can reduce the memory footprint of objects in appropriate scenarios.
  • Does not support clear(), size, keys(), values() and other methods
  • WeakMap and WeakSet are often used to store the data structure associated with the "main" object. Once the "main" object loses its meaning, the corresponding associated data structure is naturally deleted.

    【Related recommendations: javascript video tutorial, web front-end

    The above is the detailed content of Detailed explanation of JavaScript weak mapping and weak collection knowledge. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete