Does Creating Too Many Objects In Javascript Will Affect The Performance?
Solution 1:
Disclaimer: I'm a software engineer on the Chakra Javascript engine in Internet Explorer 9 and later (Hello from Building 18!)
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).
Some tips:
- If you're storing lots of simple data objects, use an array to take advantage of whatever optimizations the runtime will have. And if you are using an array, ensure all of the elements have the same underlying type (e.g. don't mix JavaScript objects with numbers in the same array).
- JavaScript is garbage-collected - which means it has all of the downsides associated with it, including pausing the entire script execution while the GC runs. If a lot of objects become available for collection all at once then the GC pause will run for a while. Watch out for memory fragmentation too.
- Avoid instance properties (i.e. use prototype properties or constructor properties), i.e.:
Bad:
for(var i = 0; i < 1000; i++ ) {
var foo = { baz: function() { return5; } };
foo.bar();
}
Good:
functionFoo() { } // `Foo` constructor.Foo.prototype.baz = function() { return5; };
for(var i=0; i < 1000; i++ ) {
var foo = newFoo();
foo.bar();
}
Also good:
functionFoo() { }
Foo.baz = function(foo) { return5; };
for(var i=0; i < 1000; i++ ) {
var foo = newFoo();
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. So this:
varObj1 = somethig;
var obj200 = something;
window.Obj1 = Obj1; // there is no `window.global` objectwindow.Obj200 = Obj200;
...doesn't actually do anything: var Obj1
is the same thing as window.Obj1
.
Finally, a protip: only give Constructor functions TitleCase
names, otherwise everything else (vars, parameters, locals, etc) lowerCase
names. Calling an instance Obj1
made my face twitch.
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!).
Post a Comment for "Does Creating Too Many Objects In Javascript Will Affect The Performance?"