Bruno Tessaro
Bruno Tessaro

Reputation: 21

Fortran performance, allocate at each subroutine call or declare a global variable and allocate once

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

Answers (2)

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

Tramplefoot
Tramplefoot

Reputation: 31

Global variables aren't recommended in this case due to two reasons:

  1. These variables are only used within the scope of a singular subroutine, setting up a global variable for this purpose is very bad code style.
  2. Allocating global variables for specific operations is bad for the expandability of your code.

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

Related Questions