Johnny Nogter
Johnny Nogter

Reputation: 33

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

Upvotes: 3

Views: 4491

Answers (3)

levik
levik

Reputation: 117529

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.

Upvotes: 5

zneak
zneak

Reputation: 138051

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.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 6

Related Questions