官术网_书友最值得收藏!

Memory management

The official definition of a WeakMap as per MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) is as follows:

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

The key emphasis is on weakly referenced. 

Before comparing Map and WeakMap, it is crucial to understand when to use a particular data structure. If you need to know the keys of the collection at any time or if you need to iterate over your collection, then you will need to use a Map over a WeakMap because keys are not enumerable, that is, you cannot get a list of the keys available in the latter, as it only maintains a weak reference.

So, naturally, the preceding statement should raise two questions in your mind:

  • What happens if I always use a map?
    • Nothing really, life goes on. You may or may not end up with memory leaks, depending on how well you have used your map. For the most part, you will be fine.
  • What is a weak reference?
    • A weak reference is something that allows everything an object refers to be garbage-collected in the event all the referrers are removed. Confused? Good. Let's take a look at the following example to understand it better:
var map = new Map();

(function() {
var key = {}; <- Object

map.set(key, 10); <- referrer of the Object

// other logic which uses the map

})(); <- IIFE which is expected to remove the referrer once executed

We all know that the IIFE is primarily used so that we can immediately execute a function and remove its scope so that we can avoid memory leaks. In this case, although we have wrapped the key and map setter in an IIFE, the key does not get garbage-collected because internally the Map still holds a reference to the key and its value:

var myWeakMap = new WeakMap();

(function() {
var key = {};<- Object

myWeakMap.
set(key, 10);<- referrer of the Object

// other logic which uses the weak map

})(); <- IIFE which is expected to remove the referrer once executed

When the same code is written with a WeakMaponce the IIFE is executed, the key and the value of that key are removed from memory because the key is taken out of scope; this helps to keep memory usage to a minimum.

主站蜘蛛池模板: 和林格尔县| 华蓥市| 怀柔区| 米林县| 庄浪县| 蒙自县| 西畴县| 山东省| 沙湾县| 澄城县| 蓝山县| 枣阳市| 监利县| 齐齐哈尔市| 古浪县| 旺苍县| 瑞昌市| 启东市| 定日县| 凤山市| 黄山市| 桃园县| 潍坊市| 涿鹿县| 沁阳市| 华阴市| 温泉县| 新巴尔虎左旗| 晴隆县| 石景山区| 凤阳县| 寿光市| 昌邑市| 五河县| 天台县| 偃师市| 太康县| 天全县| 日照市| 余干县| 寿宁县|