Johnston
Johnston

Reputation: 2873

global vars vs local vars

I have a program that constantly calls a function. In my function i use variables that are only used inside of that function. Is it better "Style" to have these variables as global so that they are not constantly being created or better to have them in the function since they are irrelevant for the rest of the program.

Thanks

Upvotes: 1

Views: 114

Answers (5)

8bitme
8bitme

Reputation: 947

I am not sure what language you are using but generally it is best practice not to declare a variable as global if it is only needed in one method.

This is also more memory efficient as the variable only uses up memory when the function that holds it is called.

Have a look at this link for more information on why global variables should be avoided when possible.

Upvotes: 1

Martin Ch
Martin Ch

Reputation: 1367

If you have classes and functions in it, its absolutely the best to have a local variables in the functions and if you need some variable, that is used in more functions in the same object set private global variables. Try to dont use global public variables, you never know who or what will change it.

Upvotes: 1

jbruni
jbruni

Reputation: 1247

The performance cost of allocating local (auto) variables is effectively nil. These variables are allocated relative to the stack pointer and are already part of your stack frame. There is no performance hit for local variables.

If you need a variable to maintain a value between calls to your function, just declare it as a static local rather than global.

Upvotes: 0

Adam Dymitruk
Adam Dymitruk

Reputation: 129526

What you are doing is correct. You want to avoid global scope variables. Let the compiler or interpreter take care of any memory usage optimization. If you go down the other road you will be in a world of hurt.

Upvotes: 2

Brett
Brett

Reputation: 4061

Standard practice would have you keep the variables within the scope that they're needed. In your case, these variables would be only local, so declare them and consume them locally. The logic for global variables would generally be for cross application access.

Upvotes: 1

Related Questions