Timing of array initialisation

A compiler has basically two approaches that it can take. One is to construct the array at compile time and store the data in static memory in the object file. For a large array, say 10x or 100x larger than in this example, that would produce a huge executable program, and just loading such a program into memory might take several minutes. Another approach would be to defer the array construction until run time. In this case, depending on how clever the compiler is with optimization, space for two such arrays might be required, one for the right hand side and one for the left hand side. Obviously this is a waste of memory, even if the array is filled at run time rather than at compile time.

I think you will find the following approach produces the smallest executable file and also executes the fastest:

integer, parameter :: N=1002001
integer, allocatable :: buildarray(:)
integer :: i
allocate( buildarray(N) )
do i = 1, N
   buildarray(i) = i
enddo

Here the compiler does everything, including the memory allocation, at run time.

1 Like