回答

  1. Map 和 Object 的相同点是都是 key-value 形式的存储结构。
  2. Map 相对于 Object 的区别主要是 3 点:
    1. Map 中的 key 可以是任意类型的值,而 Object 中的 key 只能是字符串。
    2. Map 中的 key 是有序的,而 Object 中的 key 是无序的。
    3. Map 在读取和遍历上性能更好。
  3. WeakMap 相对于 Map 的区别在于,WeakMap 对 key 是弱引用,当 key 被垃圾回收时,value 也会被回收。

    具体分析

    Map 和 Object 的区别

  4. Map 中的 key 可以是任意类型的值,而 Object 中的 key 只能是字符串。

  5. Map 中的 key 是有序的,而 Object 中的 key 是无序的。
  6. Map 在读取和遍历上性能更好。 ```typescript let a = new Map([ [“2”, 0], [“1”, 0], ]); let b = { “2”: 0, “1”: 0, };

console.log(…a.keys(), …Object.keys(b)); // 2 1 1 2

// 可以从结果中看出,map的遍历是有序的

  1. <a name="cjzwD"></a>
  2. ## Map 和 WeakMap 的区别
  3. 1. 允许的 key 类型不同,在 WeakMap 中只允许
  4. 1. WeakMap 解决了在 key 是 Object 的情况下,垃圾回收失效的问题。WeakMap 对 key 是弱引用,即垃圾回收机制不考虑此引用计数,保证在 key=null 时,key 和 value 同时被回收。
  5. 1. 为了达到对 key 的弱引用目的,WeakMap 不可遍历。
  6. ```typescript
  7. require("expose-gc");
  8. function showMemory(key: string) {
  9. global.gc();
  10. console.log(
  11. (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2),
  12. `// ${key}`
  13. );
  14. }
  15. const weakmap_key_null = () => {
  16. showMemory("_____weakmap_key_null");
  17. let key = new Array(5 * 1024 * 1024);
  18. const weakmap = new WeakMap();
  19. weakmap.set(key, 1);
  20. showMemory("创建weakmap");
  21. key = null;
  22. showMemory("weakmap,key=null");
  23. };
  24. const map_key_null = () => {
  25. showMemory("_____map_key_null");
  26. let key = new Array(5 * 1024 * 1024);
  27. const map = new Map();
  28. map.set(key, 1);
  29. showMemory("创建map");
  30. key = null;
  31. showMemory("map,key=null");
  32. };
  33. map_key_null();
  34. weakmap_key_null();
  35. // 可以从结果中看出,在 WeakMap 中 key=null,key 被正确回收;在 Map 中 key=null,key 不能被正确回收,因为在 Map 中保留了对 key 的引用,此时 map.size=1。

参考资料

  1. WeakMap - JavaScript | MDN [https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/WeakMap]