如何获取 JavaScript 对象的大小? [英] How to get the size of a JavaScript object?
问题描述
我想知道一个 JavaScript 对象占用的大小.
I want to know the size occupied by a JavaScript object.
采用以下函数:
function Marks(){
this.maxMarks = 100;
}
function Student(){
this.firstName = "firstName";
this.lastName = "lastName";
this.marks = new Marks();
}
现在我实例化student
:
var stud = new Student();
这样我就可以做类似的事情
so that I can do stuff like
stud.firstName = "new Firstname";
alert(stud.firstName);
stud.marks.maxMarks = 200;
等
现在,stud
对象将占用内存中的一些大小.它有一些数据和更多的对象.
Now, the stud
object will occupy some size in memory. It has some data and more objects.
我如何知道stud
对象占用了多少内存?类似于 JavaScript 中的 sizeof()
吗?如果我能在像 sizeof(stud)
这样的单个函数调用中找到它,那真是太棒了.
How do I find out how much memory the stud
object occupies? Something like a sizeof()
in JavaScript? It would be really awesome if I could find it out in a single function call like sizeof(stud)
.
我已经在互联网上搜索了几个月 - 找不到(在几个论坛中询问 - 没有回复).
I’ve been searching the Internet for months—couldn’t find it (asked in a couple of forums—no replies).
推荐答案
我在我的原始答案中重构了代码一>.我已经删除了递归并删除了假设的存在开销.
I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
function roughSizeOfObject( object ) {
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
这篇关于如何获取 JavaScript 对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!