Reputation: 21
I have a subroutine which allocates four vectors with size = 9, and does some operations on it. These vectors are only used inside this subroutine. The subroutine is called thousands of times during my program run.
Is it worth it to allocate the vectors each time the subroutine is called or it is better to create a global variable and only allocate the vectors once?
Upvotes: 2
Views: 319
Reputation: 60058
For very big working arrays (large 3D arrays) I do declare (global) module variables and then have a clean-up subroutine in the module handy.
However, for vectors of size 9 that really is not necessary. Allocating these on the stack as local variables costs nothing. A local variable of size 9, be it explicit or automatic, costs zero to allocate on the stack. The Fortran standard does not let you decide where the allocation happens but the compilers typically do. And stack tends to be the default.
Static storage is also possible (effectively forced by the save
attribute) but seems unnecessary here.
Upvotes: 2
Reputation: 31
Global variables aren't recommended in this case due to two reasons:
In this case, a parent subroutine can help: Do not define the vectors within a global scope, but instead, set up a parent subroutine that recieves these vectors as arguments, and let this parent subroutine call the respective (sub-)subroutines. Your vectors are defined within the scope of the parent routine, which means the parent subroutine can pass the vectors to the (sub-)subroutines without needing to access any global references. This would make your code both style-conform and (relatively) more efficient, compared to re-allocating the same vectors every time your subroutine is called.
Upvotes: 1