简体   繁体   中英

Javascript optimization…global variables

I am making a webapp. I have a fairly basic question about javascript performance. Sometimes I need a global variable to store information that is used the entire time the website is open.

An example is a variable called needs_saved. It is true or false to say whether the page needs saved. I might have another variable called is_ie, ie_version, or space_remaining.

These are all variable that I need in various functions throughout the app.

Now, I know global variables are bad because they require the browser to search each level of function scope. But, I don't know if there is any better way to store values that are needed throughout the program.

I know I could create a global object called 'program_status' and give it the properties is_ie, ie_version, etc... But is this any better since it would first have to find my program_status object (stored as a global variable), and then the internal property?

Maybe I'm overthinking this.

Thanks

You have nothing to worry about.

The performance impact of a global variable is minute.
Global variables are discouraged because they can make code harder to maintain.
In your case, they won't.

The reason global variable use should be kept to a minimum is because the global namespace gets polluted when there's a lot of them, and there's a good chance of a clash if your program needs to use some 3rd party libraries which also create their own globals.

Creating a single object to hold all of your global state is a good idea since it limits the number of identifiers you need to reserve at the global level.

To solve performance problems, you can then create a local reference to that object in any scope where you need to access it multiple times:

So instead of

if (globalState.isIe) { alert(globalState.ieMessage); }

you can do

var state = globalState;
if (state.isIe) { alert(state.ieMessage); }

You don't need to do this if you only access the state object once. In any case, even if you never do this, the performance penalties will be negligible.

If you're worried about performance, code something clean then run a profiler on it to optimize. I know both Safari and Google Chrome have one, and it's pretty sure Firebugs includes one for Firefox too. Heck, even Internet Explorer 8 has one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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