zoukankan      html  css  js  c++  java
  • [ES6] WeakMap vs Map

    WeakMap: is a type of Map where only objects can be passed as keys. Primitive data type -- such are string, numbers, booleans, etc --- are not allowed.

    let user = {};
    let comment = {};
    
    let mapSettings = new WeakMap();
    
    mapSettings.set(user, "user");
    maåSettings.set(comment, "comment");
    
    console.log(mapSettings.set(user));
    console.log(mapSettings.set(comment));

    if:

    mapSettings.set("title", "ES2015"); --> invalid value used as weap map key

    Wekmap is not iterable, therefore, they can't be used with for...of.

    WeakMaps are better with Memory:


    let user = {}; // all objects occupy memory space
    
    let userSatatus = new WeakMap();
    userStatus.set(user, "logged"); // Objecct reference passed as key to the WeakMap
    
    //...
    someOtherFunction( user );
    // Once it returns, user object can be garbage collected

    Weakmaps don't prevent the garbage colector from collecting objects currently used as keys, but that are no longer referenced anywhere else in the system.

  • 相关阅读:
    Oracle使用笔记
    跳转至锚点
    项目中使用到的AOP
    短信验证码接口使用
    阿里人脸识别接口
    java实现网页截图
    java后台接收微信服务号/订阅号消息
    java 实现redis缓存
    redis 常用命令
    被骗了,自己还不知道
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5129041.html
Copyright © 2011-2022 走看看