Page 1 of 1

Need global variables more space/RAM than local? (solved)

Posted: Sat May 20, 2006 11:50 am
by PureBaser
Hi!

It's wise to declare EVERY variable as global, whether they have to be global or not? Do it costs hard-drive speed, RAM or speed?

Posted: Sat May 20, 2006 12:06 pm
by srod
I wouldn't have thought that there would be any speed implications, but it is definitely not wise to declare all variables as being global; unless this is a very small and simple program.

Over use of global variables is asking for trouble and inviting hard to find bugs in your programs. No, in a procedural language such as PB, the isolation of functions and procedures leads to better code reuse etc. and so they do not want to be overly reliant on global variables, particularly if the procedures are to be nested in some way.

These days I wrap up my global variables in structures. E.g. I might have a global structure for user preferences, another one for GUI etc. This way, I know that any variable being used explicitly in my code is 'local' and not global. Makes bug hunting a lot easier.

Still, I'd prefer not to make any bugs at all... :D

Posted: Sat May 20, 2006 12:21 pm
by dioxin
GLOBALs are usualy very slightly faster than locals but they take up a lot more space.


GLOBALs are faster because they don't need to be created and destroyed evrytime a procedure is called and they can be accessed via a simpler addressing mechanism because their location is fixed at compile time.
LOCALs need to be created and destroyed each time and, because they exist on the stack, their position changes each time so slightly more complex addressing is needed.


GLOBALS take more space because they need to exist at all times and so they are always taking up space but LOCALs only exist while the prodedure they are declared in is active and are then deleted.


It's usually not a good idea to define everything as GLOBAL. Only do that for the few variables that need it.

Paul.

Posted: Sat May 20, 2006 12:30 pm
by PureBaser
Yeah, thats good to know...

The backgroundidea, was, to have all variables in one place for better overview, instead I will use a comments for its...

thanks!

Posted: Sat May 20, 2006 2:51 pm
by Nik
Well, believe me or not having all variable in one place is everything but not good for overview.
Better declare variables before the parts you use them(with the define statement)

Posted: Sat May 20, 2006 8:37 pm
by PureBaser
Ok... But you have rising up a new question. Has the declaration with define some disadvantages instead of use variables 'on the fly'?

Posted: Sun May 21, 2006 3:28 pm
by PureBaser
I tried and found the answer myself... it doesn't matter