TL;DR
All recursive code can be translated in an iterative form, but some algorithms are naturally recursive and more easily represented in this way.
Think, for example, of going through all the nodes of a tree or graph, processing all the files of a directory and subdirectories and so on.
In iterative mode you are responsible for manually managing the state of each step of the algorithm using some data structure, often a stack, while in recursive mode you delegate this function to your programming language, by making use of variables and parameters that are automatically allocated to the execution stack at the beginning of each method execution.
Example
To answer the questions, consider something a little more complex. I extracted the pseudo-code to traverse the trees of Wikipedia.
Recursive method
postorder(node)
if node == null then return
postorder(node.left)
postorder(node.right)
visit(node)
Iterative method
iterativePostorder(node)
parentStack = empty stack
lastnodevisited = null
while (not parentStack.isEmpty() or node ≠ null)
if (node ≠ null)
parentStack.push(node)
node = node.left
else
peeknode = parentStack.peek()
if (peeknode.right ≠ null and lastnodevisited ≠ peeknode.right)
node = peeknode.right
else
visit(peeknode)
lastnodevisited = parentStack.pop()
Answers
1st What is the advantage of using a Recursive Function?
In your example there is little advantage, but in what I put above, we see clearly that the recursive method:
- Better expresses functionality. Programming work makes everything heavy that capacity.
- Is more compact. Less code means easier maintenance, less possibility of errors and so on.
- Automatic state management. In the iterative example a stack was used (stack). Think now of languages where memory management is not automatic. In C, for example, you would have to add code to allocate and release stack elements in each iteration.
2nd How does memory consumption look?
Depends on the function. Usually you should do a memory complexity and time analysis to analyze the differences, but it is somewhat obvious that in the vast majority of cases, recursive routines consume more memory and require more execution cycles.
Recursive routines usually use more memory by reallocating variables to each recursive call, but iterative routines can use the same amount of memory if values are saved in lists or stacks, for example.
In iterative mode you have control, for better or for worse. There is the possibility of creating a more optimized routine than the recursive version. But one should not take this as a rule, after all there are excellent recursive implementations that are more efficient than the average iterative implementations.
In addition, efficiency depends greatly on the number of executions and the level of recursion. Like ordering routines, some implementations work best when there are few iterations and others when there are more iterations. Some recursive implementations are better for small processing. See for example, on this website that performance for Fibonacci where n <= 5
was better for the recursive version.
In a very simple example, the Fibonacci recursive function has complexity exponential while the version can be implemented with two or three simple variables and therefore has memory usage constant.
On the other hand, recursive routines almost always end up needing to be rewritten in their iterative version when the number of elements or numbers processed is large, after all recursiveness has a sensitive limit of both memory and data stacking.
And beyond all that, there are techniques that can improve the performance and capacity of recursive routines, examples being:
3ª Should I use a recursive function instead of a common Repetition Loop (e.g. for/while)? What would be the ideal situations for using recursive functions?
It should only be if the algorithm is best expressed recursively and if the general use of that algorithm will not exceed recursive limits.
I believe that the ideal situations have been exemplified above, that is to say:
- Inherently recursive algorithms, best expressed in this format
- Computational use is moderate so as not to exceed recursion limits
@Brunocosta you noticed the tag PHP and so it would make no sense to talk about what you are wanting?
– Maniero
@bigown I noticed too late even. Still, whether it makes sense or not is entirely up to the author of the answer.
– Bruno Costa
@Brunocosta later I’ll put something, but here it doesn’t make sense :)
– Maniero
In addition to the cases mentioned in the answers, in Desktop applications (maybe not only in these), we use recursion when we lose the connection with the Servers, Services, Database. Sometimes with trial scheme/timeout.
– Victor Tadashi