search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript weak mapping and weak collection knowledge

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 id="Summary">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. If there is any infringement, please contact admin@php.cn delete
    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

    JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

    C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

    C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

    From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

    JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

    Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.