If I have a loop like
do i = 1,much
call computations(input(i,:),output(i,:))
enddo
and
subroutine computations(inn,outt)
real, intent(in) :: inn(:)
real, intent(out) :: outt(:)
real :: temp(size(inn))
...
end subroutine
will the array temp
be allocated and deallocated on each call? We can assume that the size of input
and output
are not changing. If I did not have a subroutine but rather inline code in the loop, then this array would have to be defined higher up, and would not be reallocated on each loop iteration. Will the compiler realize this? Does it depend on optimization level/compiler?
Yes, the array will be allocated on each call. However, if it is allocated on the stack, the allocation is essentially free (just updating the stack pointer). One can never be sure about compiler optimizations unless you specify the compiler and the version, but I am not aware of any optimization like this, that would be very complicated. And also we would have to know the size of the array and whether the compiler allocates on the stack or on the heap.
If the subroutine is internal, you can allocate the array higher up. You can also allocate it higher up and pass it as an argument. But only do that if it really brings anything. If it is a rather small stack array, it would not achieve much.