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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.194.182