实现sizeof()函数,传入一个参数object,计算这个object占用了多少字节

注意点:

  •  number类型:8字节
  •  string类型:每个长度是2字节
  •  boolean类型:4字节
  • 对象的key也是占内存的
  • 对象被多次引用时,内存只被计算一次

        const xxx = {
            name: 'zs'
        }
        const testData = {
            a: 111,
            b: 'cccc',
            22222: false,
            1111: xxx,
            3333: xxx
        }
        // number:8字节
        // string:每个长度是2字节
        // boolean:4字节
        const seen = new WeakSet()
        function sizeOfObject(object) {
            if (object === null) {
                return 0
            }
            let bytes = 0
            // 注意:对象key也是占内存的
            // 对象的key
            const properties = Object.keys(object)
            for (let i = 0; i < properties.length; i++) {
                const key = properties[i]
                // 对象key所占字节
                bytes += calculator(key)
                // 对象的value
                const value = object[key]
                if (typeof value === 'object' && value !== null) {
                    // 如果value的对象被引用过则跳过,不再重复计算内存
                    if (seen.has(value)) {
                        continue
                    }
                    seen.add(value)
                }
                // 对象value所占字节
                bytes += calculator(value)
            }
            return bytes
        }
        function calculator(object) {
            // 判断要监测的数据的类型
            const objectType = typeof object
            switch (objectType) {
                case 'string': {
                    return object.length * 2
                }
                case 'number': {
                    return 8
                }
                case 'boolean': {
                    return 4
                }
                case 'object': {
                    if (Array.isArray(object)) {
                        // 对数组的处理
                        // 注意:数组可能是[1,2,3,4]也可能是[{},{}]
                        return object.map(calculator).reduce((res, current) => res + current, 0)
                    } else {
                        //对对象的处理
                        return sizeOfObject(object)
                    }
                }
                default: {
                    return 0
                };
            }
        }
        console.log(calculator(testData));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值