When to declare

Smee

Well-Known Member
Licensed User
Longtime User
In other programming languages I was always taught to Dim variables early in the program and only in subroutines if the subroutine was only called infrequently. So even though a variable may only be used in one or two routines if it is called frequently then it should be Dim once and initialised going into the routine.
For example in Globals Dim m as Map,a as int

In the sub routines

m.initialise
a=0

Is this considered "good" programmiong practice in B4A and more importantly is it more or less efficient use of memory

Thanks
 

moster67

Expert
Licensed User
Longtime User
I think it is more a question of scope. Why declare a variable in globals if it is only used in a sub-routine (unless for instance library-instructions says it should be in globals)?

Sent from my HTC HD2
 
Upvote 0

Smee

Well-Known Member
Licensed User
Longtime User
Thanks for the reply,

Why declare a variable in globals if it is only used in a sub-routine (unless for instance library-instructions says it should be in globals)?

I am wondering which is the most efficient use of memory. Is it better to declare once and use it reguarly or keep declaring the variable each time the subroutine is entered?

Cheers
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
Best practice is to minimise the scope of variables so only put things in globals that need to be there. It reduces visual clutter and aids understanding.

The overhead of declaring local primitive types and arrays of primitive types is very small and should not be of concern to you. Also local primitive variables are located on the stack and only occupy memory when the execution is within the scope of the Sub. Local arrays are located in managed memory but the memory is reclaimed when the Sub exits unless a reference is kept to the array outside the Sub. Global variables are present in memory all the time.
 
Upvote 0

thedesolatesoul

Expert
Licensed User
Longtime User
Thanks for the reply,



I am wondering which is the most efficient use of memory. Is it better to declare once and use it reguarly or keep declaring the variable each time the subroutine is entered?

Cheers

This probably dependent on the memory model your programming language uses.
For Java and B4A, I think there is regular garbage collection. Unused variables/objects will be deallocated. So if you call your sub infrequently, the memory allocated will be lesser. If you call it alot then those variables will re-allocated memory and de-allocate memory (when garbage collection is done).

I would however declare variables based on their scope rather than worrying about the underlying implementations.

EDIT: Again! agraham beat me to it.
 
Upvote 0
Top