Optimization of initialization function
I usually break down the parts of my app into their own modu开发者_如何学Cles and files that exist under one global object. For the production code I combine all the files on one master.js file. Because I'm writing the code in different files and don't want to worry about the order they're loaded I check if the global object 'App' exists, and if it doesn't create an empty object to store the module in.
So if I have 10 modules then in the combined file it will run var App = App || {};
10 times when it only needs to run once (at the start). My question is, is that a big deal in terms of performance, is it worth going in at the end and removing the unnecessary code? For smaller apps I don't think it's a big deal, but just wondering if this is a bad strategy to use for bigger apps.
// module_1.js
var App = App || {};
App.Module_1 = (function(){
// code
}());
// module_2.js (different file)
var App = App || {};
App.Module_2 = (function(){
// code
}());
Even if var App = App || {}
runs 100 times, you will not notice any difference (only on very slow systems), so I'd say: just leave it.
Generally, don't optimize prematurely, look where the real bottlenecks are and optimize those.
BTW, those extra anonymous, self-invoking functions are not necessary: when using
App.Module_X = function(){
// code
};
you variables declared using var
already are within the scope of App.Module_X
.
精彩评论