I have came across a concept in recursion which says that when loops are compiled or interpreted then they get converted to recursive functions. If it is true how it takes place ?
1 Answer
It depends. In many language implementations, using recursion for loops is a good way to cause a Stack Overflow as each call adds more and more entries to the stack until it eventually runs out. Some implementations get around that by taking advantage of their design combined with the Tail Call Optimization, which is effectively reusing the current stack entry because you know it will no longer be needed.
That though is rare. Most implementations simply convert the loop into properly positioned goto statements (or jump instructions depending on your perspective) so instructions are repeated.
And certain implementations in certain situations will do an optimization called Loop Unrolling where they effectively copy the code for the number of iterations of the loop rather than do either of these options. That though generally requires the number of iterations to be known at compile time and is impractical for big loops (either in instructions or iterations).
-
I've seen a loop unrolling strategy that worked at runtime. Basically, the program figured out how many times through the loop right before entering it, and then it jumped into the unrolled loop at the appropriate place for it to come out at the right time. I thought it was pretty common for compilers to do that even for generic cases, so long as the code could figure out the iteration count before entering the loop.Ed Grimm– Ed Grimm2019-02-06 06:37:59 +00:00Commented Feb 6, 2019 at 6:37
-
2Nitpick: all mentions of the term "language" in the last two paragraphs should be "compiler". Languages don't compile or loop unroll, compilers do. Two different compilers for the same language may in the same situation for the same code make different decisions about whether or not to perform loop unrolling, for example.Jörg W Mittag– Jörg W Mittag2019-02-06 09:16:52 +00:00Commented Feb 6, 2019 at 9:16
-
@JörgWMittag - good point; edited.Telastyn– Telastyn2019-02-06 15:41:44 +00:00Commented Feb 6, 2019 at 15:41
Jump, this is actually not a traditional jump instruction, but a tail call.