Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29274 Discussions

Is there a penalty (in terms of speed) associated with the use of RECURSIVE subroutines?

OP1
New Contributor III
613 Views
I am wondering if using RECURSIVE subroutines is a good practice. I have the following code:

RECURSIVE SUBROUTINE MY_RECURSIVE_SUB(A,ALPHA,ALPHA_TARGET,D_ALPHA_MAX,FLAG)
USE MODULE_WHERE_T_COMPLICATED_STRUCTURE_IS_DEFINED
IMPLICIT NONE
TYPE(T_COMPLICATED_STRUCTURE),INTENT(INOUT) :: A
LOGICAL,INTENT(IN) ::FLAG
REAL(KIND=8),INTENT(INOUT) :: ALPHA,ALPHA_TARGET,D_ALPHA_MAX
...
IF (FLAG) THEN
IF (ABS(ALPHA-ALPHA_TARGET)>D_ALPHA_MAX) THEN
CALL MY_RECURSIVE_SUB(A,ALPHA,ALPHA_TARGET,D_ALPHA_MAX,.FALSE.)
ALPHA_TARGET = ALPHA
ELSE
... do some work with A ...
ENDIF
ELSE
... do some workwith A ...
ENDIF
END SUBROUTINE MY_RECURSIVE_SUB

A is a very large and complicated derived type structure which contains allocatable arrays, other derived type variables, etc. When the subroutine recursively calls itself,is a copy of Amade? Is there a speed penalty associated with such a coding approach?

Thanks,

Olivier
0 Kudos
4 Replies
TimP
Honored Contributor III
613 Views
It certainly appears that all these data must be replicated on stack for each recursive call. I don't see that a generalization could be made about the performance, even if I assume that your alternative is an array of those "complicated structures." If there is no reason for each instance to have its own copy of those arrays, it seems you could get better cache locality by sharing a single copy, if only one thread is involved.
0 Kudos
OP1
New Contributor III
613 Views
Thanks Tim18, I had the gut feeling it would be a no-go. I'll restructure my code to avoid this need for recursivity.

Olivier
0 Kudos
Steven_L_Intel1
Employee
613 Views

Unless I'm misreading this, no copies are made. You are simply passing along the dummy arguments to a routine whose explicit interface is known, so it would just pass the same item by reference. RECURSIVE allows local variables to be distinct, but I don't see any in this excerpt. It would also ensure correct behavior for any locally created descriptors or pointers.
0 Kudos
OP1
New Contributor III
613 Views
Oh, I see. Yes, it definitely makes sense that the local variables are duplicated.The dummy arguments do not need to (which is what I was concerned about).

Thanks Steve for clarifying this.

Olivier
0 Kudos
Reply