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

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.

主站蜘蛛池模板: 永嘉县| 贵州省| 东城区| 长沙县| 当阳市| 临泽县| 西盟| 梅河口市| 武夷山市| 大丰市| 张家港市| 垣曲县| 堆龙德庆县| 建昌县| 塘沽区| 阿拉善盟| 晋宁县| 肃宁县| 张掖市| 开阳县| 延寿县| 洛浦县| 揭东县| 资中县| 突泉县| 凤冈县| 万安县| 南和县| 巫山县| 黑山县| 荔浦县| 锡林郭勒盟| 张掖市| 牡丹江市| 云南省| 西林县| 贵港市| 温泉县| 拉孜县| 彰化县| 承德县|