dbabaioff
dbabaioff

Reputation: 268

Memory usage of JavaScript objects

If I have an array of three objects:

var array = [obj1, obj2, obj3];

And my objects has one specific property (example: "id") and two common properties (example: "prop" and "log" function)..

I wonder which one would have least memory usage? What's better to use?

Defining the same properties on all items of my array:

var obj1 = {id: 1, prop: '@', log: function() { console.log('TEST'); }};
var obj2 = {id: 2, prop: '@', log: function() { console.log('TEST'); }};
var obj3 = {id: 3, prop: '@', log: function() { console.log('TEST'); }};

var array = [obj1, obj2, obj3];

vs.

Creating objects (items of my array) with a given prototype

var myProto = {prop: '@', log: function() { console.log('TEST'); }};

var obj1 = Object.create(myProto);
obj1.id = 1;

var obj2 = Object.create(myProto);
obj2.id = 2;

var obj3 = Object.create(myProto);
obj3.id = 3;

var array = [obj1, obj2, obj3];

vs.

Create a object with the common properties and extend my array items to use this object

var common = {prop: '@', log: function() { console.log('TEST'); }};

var obj1 = extend({id: 1}, common);
var obj2 = extend({id: 2}, common);
var obj3 = extend({id: 3}, common);

var array = [obj1, obj2, obj3];

Upvotes: 2

Views: 527

Answers (2)

Harazi
Harazi

Reputation: 122

Case one - you are creating 3 separate objects with different properties (while prop and log looks the same, they have nothing in common).

Case two - here you are using prototype. Properties and functions are common to all of the objects that shares this prototype.

Case three - you are extending your object, meaning copying properties and references. You definitely don't want to go this way in your case. Although it might be useful if you want to exactly that, but you may end up creating memory leaks, since when you are disposing of objects - you have to detach all of the references to other objects and functions.

Conclusion, use prototypes to share stuff between the objects.

Upvotes: 0

Greg Burghardt
Greg Burghardt

Reputation: 18928

From a memory standpoint, using a prototype would be more efficient. Secondly, since you want to initialize a property in each of the new objects, you may have a case for constructor functions.

function Foo(id) {
    this.id = id || null;
}

Foo.prototype = {

    id: null,

    prop: "@",

    constructor: Foo,

    log: function() {
        console.log("TEST");
    }

};

var array = [
    new Foo(1),
    new Foo(2),
    new Foo(3)
];

Upvotes: 1

Related Questions