Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing "size" property for WeakMaps. But is this true? What's the difference between them?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
WeapMap in javascript does not hold any keys or values, it just manipulate key value using a unique id and define property to key object.
because it define property to
key
by methodObject.definePropert()
, key must not be primitive type.and also because WeapMap does not contain actually key value pairs, we cannot get length property of weakmap.
and also manipulated value is assigned back to key, garbage collector easily can collect key if it in no use.
Sample code for implementation.
reference of implementation
They both behave differently when a object referenced by their keys/values gets deleted. Lets take the below example code:
The above IIFE is executed there is no way we can reference
{x: 12}
and{y: 12}
anymore. Garbage collector goes ahead and deletes the key b pointer from “WeakMap” and also removes{y: 12}
from memory. But in case of “Map”, the garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove{x: 12}
from memory.Summary: WeakMap allows garbage collector to do its task but not Map.
References: http://qnimate.com/difference-between-map-and-weakmap-in-javascript/
Maybe the next explanation will be more clear for someone.
As you see, after removing
k1
key from the memory we can still access it inside the map. At the same time removingk2
key of WeakMap removes it fromwm
as well by reference.That's why WeakMap hasn't enumerable methods like forEach, because there is no such thing as list of WeakMap keys, they are just references to another objects.
From the very same page, section "Why Weak Map?":
[And that's why they have no
size
property as well]‐ which would be the "normal"
Map
s. Not mentioned at MDN, but in the harmony proposal, those also haveitems
,keys
andvalues
generator methods and implement theIterator
interface.Another difference:
Nor can a string, number, or boolean be used as a
WeakMap
key. AMap
can use primitive values for keys.