Home Web Front-end JS Tutorial Using ES6 to solve the memory leak problem through WeakMap (detailed tutorial)

Using ES6 to solve the memory leak problem through WeakMap (detailed tutorial)

May 31, 2018 pm 03:30 PM
Memory solve

This article mainly introduces the detailed explanation of ES6's solution to the memory leak problem through WeakMap. Now I share it with you and give it as a reference.

1. Map

#1. Define the

Map object to save key-value pairs, similar to For data structure dictionaries; unlike traditional objects that can only use strings as keys, Map objects can use any value as a key.

2. Syntax

new Map([iterable])
Copy after login

Attribute

size: Returns the number of key-value pairs.

Operation method

  1. set(key, value): Set (add/update) the value of the key key to value and return the Map object.

  2. get(key): Read the value of key key, if not, return undefined.

  3. has(key): Determine whether a key-value pair exists in a Map object and return true/false.

  4. delete(key): Delete a key-value pair and return true/false.

  5. clear(): Clear all key-value pairs in the Map object.

Traversal method

  1. keys(): Returns the Iterator object of the key name.

  2. values(): Returns the Iterator object of the key value.

  3. entries(): Returns an Iterator object of key-value pairs.

  4. forEach((value, key, map) => {}): Traverse all key-value pairs of the Map object.

3. Example

Operation method

let m = new Map([
  ['foo', 11],
  ['bar', 22]
]);
m.set('mazey', 322)
  .set('mazey', 413);
console.log(m); // {"foo" => 11, "bar" => 22, "mazey" => 413}
console.log(m.has('mazey')); // true
m.delete('mazey');
console.log(m.has('mazey')); // false
m.clear();
console.log(m); // {}
Copy after login

Traversal method

let m = new Map([
  ['foo', 11],
  ['bar', 22],
  ['mazey', 413]
]);
console.log(m); // {"foo" => 11, "bar" => 22, "mazey" => 413}
console.log(m.keys()); // MapIterator {"foo", "bar", "mazey"}
console.log(m.values()); // MapIterator {11, 22, 413}
console.log(m.entries()); // MapIterator {"foo" => 11, "bar" => 22, "mazey" => 413}
m.forEach((value, key, map) => {
  console.log("键:%s,值:%s", key, value);
});
// 键:foo,值:11
// 键:bar,值:22
// 键:mazey,值:413
Copy after login

2. WeakMap

1. Definition

WeakMap object saves key-value pairs. Unlike Map, its key must be an object, because The key is a weak reference, and the memory is automatically released after the key object disappears.

2. Syntax

new WeakMap([iterable])
Copy after login

Method

  1. set(key, value): Set (new/update) key The value of key is value and a WeakMap object is returned.

  2. get(key): Read the value of key key, if not, return undefined.

  3. has(key): Determine whether a key-value pair exists in a WeakMap object and return true/false.

  4. delete(key): Delete a key-value pair and return true/false.

Note

Because of the special garbage collection mechanism of WeakMap, there is no clear() method.

3. Example

let obj = {
  foo: 11
};
let wm = new WeakMap();
wm.set(obj, 413322);
console.log(wm); // {{…} => 413322}
console.log(wm.has(obj)); // true
Copy after login

3. Solve the memory leak problem through WeakMap

When used When the Dom object binds events, if the memory is not released in time (set to null) after the Dom object disappears, it will always exist in the memory.

Using WeakMap to save Dom objects will not cause such problems, because after the Dom object disappears, the JS garbage collection mechanism will automatically release the memory it occupies.

<button type="button" id="btn">按钮</button>
<script>
let wm = new WeakMap();
let btn = document.querySelector(&#39;#btn&#39;);
wm.set(btn, {count: 0});
btn.addEventListener(&#39;click&#39;, () => {
  let v = wm.get(btn);
  v.count++;
  console.log(wm.get(btn).count);
});
// 1 2 3 4 5...
</script>
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Example of vue combined with Echarts to achieve click highlighting effect

Vue method to obtain the currently activated route

detailed explanation of echarts mouse overlay highlighting node and relationship names

The above is the detailed content of Using ES6 to solve the memory leak problem through WeakMap (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Five tips to teach you how to solve the problem of Black Shark phone not turning on! Five tips to teach you how to solve the problem of Black Shark phone not turning on! Mar 24, 2024 pm 12:27 PM

As smartphone technology continues to develop, mobile phones play an increasingly important role in our daily lives. As a flagship phone focusing on gaming performance, the Black Shark phone is highly favored by players. However, sometimes we also face the situation that the Black Shark phone cannot be turned on. At this time, we need to take some measures to solve this problem. Next, let us share five tips to teach you how to solve the problem of Black Shark phone not turning on: Step 1: Check the battery power. First, make sure your Black Shark phone has enough power. It may be because the phone battery is exhausted

Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Large memory optimization, what should I do if the computer upgrades to 16g/32g memory speed and there is no change? Jun 18, 2024 pm 06:51 PM

For mechanical hard drives or SATA solid-state drives, you will feel the increase in software running speed. If it is an NVME hard drive, you may not feel it. 1. Import the registry into the desktop and create a new text document, copy and paste the following content, save it as 1.reg, then right-click to merge and restart the computer. WindowsRegistryEditorVersion5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SessionManager\MemoryManagement]"DisablePagingExecutive"=d

How to check memory usage on Xiaomi Mi 14Pro? How to check memory usage on Xiaomi Mi 14Pro? Mar 18, 2024 pm 02:19 PM

Recently, Xiaomi released a powerful high-end smartphone Xiaomi 14Pro, which not only has a stylish design, but also has internal and external black technology. The phone has top performance and excellent multitasking capabilities, allowing users to enjoy a fast and smooth mobile phone experience. However, performance will also be affected by memory. Many users want to know how to check the memory usage of Xiaomi 14Pro, so let’s take a look. How to check memory usage on Xiaomi Mi 14Pro? Introduction to how to check the memory usage of Xiaomi 14Pro. Open the [Application Management] button in [Settings] of Xiaomi 14Pro phone. To view the list of all installed apps, browse the list and find the app you want to view, click on it to enter the app details page. In the application details page

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sources say Samsung Electronics and SK Hynix will commercialize stacked mobile memory after 2026 Sep 03, 2024 pm 02:15 PM

According to news from this website on September 3, Korean media etnews reported yesterday (local time) that Samsung Electronics and SK Hynix’s “HBM-like” stacked structure mobile memory products will be commercialized after 2026. Sources said that the two Korean memory giants regard stacked mobile memory as an important source of future revenue and plan to expand "HBM-like memory" to smartphones, tablets and laptops to provide power for end-side AI. According to previous reports on this site, Samsung Electronics’ product is called LPWide I/O memory, and SK Hynix calls this technology VFO. The two companies have used roughly the same technical route, which is to combine fan-out packaging and vertical channels. Samsung Electronics’ LPWide I/O memory has a bit width of 512

Samsung announced the completion of 16-layer hybrid bonding stacking process technology verification, which is expected to be widely used in HBM4 memory Samsung announced the completion of 16-layer hybrid bonding stacking process technology verification, which is expected to be widely used in HBM4 memory Apr 07, 2024 pm 09:19 PM

According to the report, Samsung Electronics executive Dae Woo Kim said that at the 2024 Korean Microelectronics and Packaging Society Annual Meeting, Samsung Electronics will complete the verification of the 16-layer hybrid bonding HBM memory technology. It is reported that this technology has passed technical verification. The report also stated that this technical verification will lay the foundation for the development of the memory market in the next few years. DaeWooKim said that Samsung Electronics has successfully manufactured a 16-layer stacked HBM3 memory based on hybrid bonding technology. The memory sample works normally. In the future, the 16-layer stacked hybrid bonding technology will be used for mass production of HBM4 memory. ▲Image source TheElec, same as below. Compared with the existing bonding process, hybrid bonding does not need to add bumps between DRAM memory layers, but directly connects the upper and lower layers copper to copper.

Micron: HBM memory consumes 3 times the wafer volume, and production capacity is basically booked for next year Micron: HBM memory consumes 3 times the wafer volume, and production capacity is basically booked for next year Mar 22, 2024 pm 08:16 PM

This site reported on March 21 that Micron held a conference call after releasing its quarterly financial report. At the conference, Micron CEO Sanjay Mehrotra said that compared to traditional memory, HBM consumes significantly more wafers. Micron said that when producing the same capacity at the same node, the current most advanced HBM3E memory consumes three times more wafers than standard DDR5, and it is expected that as performance improves and packaging complexity intensifies, in the future HBM4 This ratio will further increase. Referring to previous reports on this site, this high ratio is partly due to HBM’s low yield rate. HBM memory is stacked with multi-layer DRAM memory TSV connections. A problem with one layer means that the entire

Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan Lexar launches Ares Wings of War DDR5 7600 16GB x2 memory kit: Hynix A-die particles, 1,299 yuan May 07, 2024 am 08:13 AM

According to news from this website on May 6, Lexar launched the Ares Wings of War series DDR57600CL36 overclocking memory. The 16GBx2 set will be available for pre-sale at 0:00 on May 7 with a deposit of 50 yuan, and the price is 1,299 yuan. Lexar Wings of War memory uses Hynix A-die memory chips, supports Intel XMP3.0, and provides the following two overclocking presets: 7600MT/s: CL36-46-46-961.4V8000MT/s: CL38-48-49 -1001.45V In terms of heat dissipation, this memory set is equipped with a 1.8mm thick all-aluminum heat dissipation vest and is equipped with PMIC's exclusive thermal conductive silicone grease pad. The memory uses 8 high-brightness LED beads and supports 13 RGB lighting modes.

See all articles