John Kiernander
John Kiernander

Reputation: 4904

Performance impact of instanced objects in Javascript

I have an application which currently calculates and stores data in the following way (obviously the case here has been very simplified, in reality there are many more properties in the inner object):

var processedData = [];
sourceData.forEach(function (d) {
    processedData.push({
       a: getA(d),
       b: getB(d),
       c: getC(d)
    });
}, this);
function DoStuff(row) {
    // Do Some Stuff
}

The number of objects created here can be high (thousands), performance is fine with the current approach but in the wider context I think it would really improve code readability and testability if I moved to a more defined object format:

var row = function (a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.DoStuff = function () {
        // Do Some Stuff
    }
};
var processedData = [];
sourceData.forEach(function (d) {
    processedData.push(new row(
       getA(d),
       getB(d),
       getC(d)
    ));
}, this);

There are two elements I'm worried about here, one is the performance/memory cost of constructing an instanced object with new. The second is the memory cost of including a function in the object which will have thousands of instances. I'm not sure how clever JavaScript is with that kind of thing.

Upvotes: 1

Views: 59

Answers (1)

Eugene P.
Eugene P.

Reputation: 2625

Re organization a bit to prototype. Only one function instead of thousands

function Row (a, b, c) {
    this.a = a;
    this.b = b;
    this.c = c;
}

Row.prototype.DoStuff = function () {
    // do stuff
}

I will suggest to use for, instead of foreach. it's not sensible for small collection, but for big ones make sense

It depends on HOW you'd like to work with your collection. If you don't bother about sorting, grouping,etc. stuff, but need some random key access -you can try to create a hash object, having some field as key like below

function getValue(key) {
 return hash[key];
}
var hash = { 
 "key1" : { "a" : 1 , "b" : 2 , "c" : 3 }, 
 "key2" : { "a" : 1 , "b" : 2 , "c" : 3 }
};

Not sure what is getA, getB, getC - probably it also can be re engineered

hope that helps

Upvotes: 1

Related Questions