简体   繁体   English

Javascript中实例化对象的性能影响

[英]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. 我在这里担心两个因素,一个是使用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. 我不确定这种事情的JavaScript有多聪明。

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. 我建议使用for,而不是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 不确定什么是getA,getB,getC-可能还可以重新设计

hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM