Reputation: 764
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. Will it affect the performance of webb app?
var Obj1 = somethig;
var obj200 = something;
window.global.Obj1 = Obj1;
window.global.Obj200 = Obj200;
Upvotes: 2
Views: 3479
Reputation: 155648
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:
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. 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
.
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!).
Upvotes: 11