乐闻世界logo
搜索文章和话题

What 's the difference between ES6 Map and WeakMap?

1个答案

1

In JavaScript ES6, both Map and WeakMap are collections used for storing key-value pairs, but they have several key differences:

  1. Key Types:

    • Map can accept various types of values as keys, including objects and primitive data types (such as numbers, strings, and other types).
    • WeakMap keys must be objects and cannot be other primitive data types.
  2. Weak References:

    • Keys in WeakMap are weak references to objects, meaning that if no other references point to the object, it can be garbage collected. This characteristic makes WeakMap an effective tool for managing and optimizing memory, especially when dealing with large numbers of objects and caching scenarios.
    • In contrast, keys in Map are strong references, and as long as the Map instance exists, the keys and values will not be garbage collected.
  3. Enumerability:

    • The contents of Map can be iterated, and you can use Map methods such as .keys(), .values(), and .entries() to access keys, values, or key-value pairs.
    • WeakMap does not support iteration and lacks these methods, and there is no way to clearly determine the number of elements in WeakMap. This is because the references to objects are weak; enumerating them would expose the garbage collector's state, leading to unpredictable behavior.
  4. Use Cases:

    • Map is suitable for scenarios requiring frequent lookups and can store additional information, such as mappings between user IDs and user data.
    • WeakMap is commonly used for caching or storing information relevant only when the object exists, such as private data or cached objects, without hindering garbage collection.

Example:

Consider a scenario where we need to manage metadata for an object, where the metadata should only exist while the object is active.

Using WeakMap:

javascript
let weakMap = new WeakMap(); let obj = {}; // Set object's metadata weakMap.set(obj, { metadata: "Some data" }); console.log(weakMap.get(obj)); // Output: { metadata: "Some data" } // When obj is no longer referenced, garbage collection automatically clears the key and value obj = null; // weakMap may now be empty

Using Map will not automatically clean up; even if obj is no longer referenced, its metadata will remain in the Map, potentially leading to memory leaks.

2024年6月29日 12:07 回复

你的答案