[英]Does creating too many objects in javascript will affect the performance?
I am developing a web app and creating many objects in JavaScript, which I need to maintain throughout the session or when the website is open and I am making all objects referencing to a single global object. 我正在开发一个Web应用程序并使用JavaScript创建许多对象,在整个会话过程中或网站打开时都需要维护这些对象,并且使所有对象都引用一个全局对象。 Will it affect the performance of webb app?
它会影响webb应用程序的性能吗?
var Obj1 = somethig;
var obj200 = something;
window.global.Obj1 = Obj1;
window.global.Obj200 = Obj200;
Disclaimer: I'm a software engineer on the Chakra Javascript engine in Internet Explorer 9 and later (Hello from Building 18!) 免责声明:我是Internet Explorer 9及更高版本中Chakra Javascript引擎的软件工程师(来自Building 18的Hello!)
In short: "it depends" - we need to know how many objects you're creating, how complex they are (as JavaScript does not have classes, but prototypes and instances), how frequently you're creating them, and if your script/program would cause the GC to collect the objects (and GC runs aren't pretty). 简而言之:“取决于”-我们需要知道您正在创建多少个对象,它们有多复杂(因为JavaScript没有类,但是有原型和实例),创建它们的频率以及您的脚本是否/ program会导致GC收集对象(并且GC运行不正常)。
Some tips: 一些技巧:
Bad: 坏:
for(var i = 0; i < 1000; i++ ) {
var foo = { baz: function() { return 5; } };
foo.bar();
}
Good: 好:
function Foo() { } // `Foo` constructor.
Foo.prototype.baz = function() { return 5; };
for(var i=0; i < 1000; i++ ) {
var foo = new Foo();
foo.bar();
}
Also good: 也不错:
function Foo() { }
Foo.baz = function(foo) { return 5; };
for(var i=0; i < 1000; i++ ) {
var foo = new Foo();
Foo.bar( foo );
}
As for your code example, if you're in the root scope (called global
, which in browsers is aliased by the window
object) then the var
keyword has the effect of making a property. 对于您的代码示例,如果您位于根范围(称为
global
,在浏览器中由window
对象作为别名),则var
关键字具有创建属性的作用。 So this: 所以这:
var Obj1 = somethig;
var obj200 = something;
window.Obj1 = Obj1; // there is no `window.global` object
window.Obj200 = Obj200;
...doesn't actually do anything: var Obj1
is the same thing as window.Obj1
. ...实际上并没有做任何事情:
var Obj1
是一回事window.Obj1
。
Finally, a protip: only give Constructor functions TitleCase
names, otherwise everything else (vars, parameters, locals, etc) lowerCase
names. 最后,一个提示:仅给构造函数提供
TitleCase
名称,否则给其他所有名称(变量,参数, TitleCase
变量等) lowerCase
名称。 Calling an instance Obj1
made my face twitch. 调用一个实例
Obj1
使我的脸抽搐。
As always, the golden rule applies: premature optimisation is the root of all evil - profile your code first to see if there's a problem before making significant changes to your code (and IE 11's F12 tools are great for inspecting the memory and processing performance of your code, btw - not that I'm unbiased!). 一如往常,黄金法则适用:过早的优化是万恶之源 -在对代码进行重大更改之前先分析代码,看是否有问题(而IE 11的F12工具非常适合检查内存和处理性能)。顺便说一句-并不是说我没有偏见!)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.