-
Notifications
You must be signed in to change notification settings - Fork 0
/
memorySizeOf.js
53 lines (47 loc) · 1.1 KB
/
memorySizeOf.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function memorySizeOf(obj) {
var bytes = 0;
function sizeOf(obj) {
if(obj !== null && obj !== undefined) {
switch(typeof obj) {
case 'number':
bytes += 8;
break;
case 'string':
bytes += obj.length * 2;
break;
case 'boolean':
bytes += 4;
break;
case 'object':
var objClass = Object.prototype.toString.call(obj).slice(8, -1);
if(objClass === 'Object' || objClass === 'Array') {
for(var key in obj) {
if(!obj.hasOwnProperty(key)){
continue;
}
sizeOf(obj[key]);
}
} else{
bytes += obj.toString().length * 2;
}
break;
}
}
return bytes;
};
function formatByteSize(bytes) {
if(bytes < 1024){
return bytes + " bytes";
}
else if(bytes < 1048576){
return(bytes / 1024).toFixed(3) + " KiB";
}
else if(bytes < 1073741824){
return(bytes / 1048576).toFixed(3) + " MiB";
}
else{
return(bytes / 1073741824).toFixed(3) + " GiB";
}
};
return formatByteSize(sizeOf(obj));
};