如何获得JavaScript对象的大小? [英] How to get the size of a JavaScript object?

查看:152
本文介绍了如何获得JavaScript对象的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道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();
}

现在我实例化学生

var stud = new Student();

这样我可以做点什么

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆