Michael Lewis
Michael Lewis

Reputation: 4302

How much memory is an empty JavaScript object?

Option A:

myobj = {
    a: 'a',
    a1: 'a1',
    a2: 'a2',
    a2a: 'a2a',
    a2b: 'a2b',
    a3: 'a3',
    a3a: 'a3a',
    a3a1: 'a3a1',
    a3a2: 'a3a2',
    b: 'b',
    // ...
};

vs. Option B:

myobj = {
    a: {
        a1: 'a1',
        a2: {
            a2a: 'a2a',
            a2b: 'a2b'
        },
        a3: {
            a3a: {
                a3a1: 'a3a1',
                a3a2: 'a3a2'
            }
        }
    },
    b: { ... }
};

I'm weighing this as a design decision. Here's a simpler case:

Option A:

eventHandler: {
    triggerObj: triggerObj,
    triggerAction: triggerObj.someMethod,
    responseObj: responseObj,
    responseAction: responseObj.someMethod
}

vs. Option B:

eventHandler: {
    trigger: {
        obj: triggerObj,
        action: triggerObj.someMethod
    },
    response: {
        obj: responseObj,
        action: responseObj.someMethod
    }
}

I'm pretty sure this is like the eye doctor: they're so close, it doesn't really matter. However, thought I'd see if there are any solid reasons for performance, or just for semantic/readability/other.

Relating back to the question title: how many extra object braces would be necessary to have a notable performance issue? I doubt even a few 1000 or even a 1,000,000 would matter much :-\

Upvotes: 2

Views: 1541

Answers (1)

Robert Martin
Robert Martin

Reputation: 17177

I went ahead and did it. I created an empty object, and into it I put 1 million empty objects. Then I opened profiler.

Object count: 1,011,296
Shallow size: 12,202,312
Retained size: 14,434,484

So each empty JavaScript object is about 12 bytes. I also tried it with empty array objects:

Array count: 1,000,725
Shallow size: 32,023,200
Retained size: 32,034,880

Empty array objects take up about 32 bytes.

Upvotes: 4

Related Questions