注意点:
- 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));