<p>Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome.
I have seen many programmers using recursion as a means to show off when a simple iteration algorithm can fit the bill.
Does the compiler play a vital role in deciding what to use?</p>

[{'answer_id': 72231, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on the language. In Java you should use loops. Functional languages optimize recursion.</p>\n'}, {'answer_id': 72274, 'author': 'MovEaxEsp', 'author_id': 5308, 'author_profile': 'https://Stackoverflow.com/users/5308', 'pm_score': 3, 'selected': False, 'text': '<p>Using recursion, you\'re incurring the cost of a function call with each "iteration", whereas with a loop, the only thing you usually pay is an increment/decrement.  So, if the code for the loop isn\'t much more complicated than the code for the recursive solution, loop will usually be superior to recursion.  </p>\n'}, {'answer_id': 72279, 'author': 'metadave', 'author_id': 7237, 'author_profile': 'https://Stackoverflow.com/users/7237', 'pm_score': 2, 'selected': False, 'text': '<p>I would think in (non tail) recursion there would be a performance hit for allocating a new stack etc every time the function is called (dependent on language of course).</p>\n'}, {'answer_id': 72333, 'author': 'Doron Yaacoby', 'author_id': 3389, 'author_profile': 'https://Stackoverflow.com/users/3389', 'pm_score': 4, 'selected': False, 'text': '<p>Recursion is more costly in memory, as each recursive call generally requires a memory address to be pushed to the stack - so that later the program could return to that point. </p>\n\n<p>Still, there are many cases in which recursion is a lot more natural and readable than loops - like when working with trees. In these cases I would recommend sticking to recursion.</p>\n'}, {'answer_id': 72363, 'author': 'zweiterlinde', 'author_id': 6592, 'author_profile': 'https://Stackoverflow.com/users/6592', 'pm_score': 4, 'selected': False, 'text': '<p>Typically, one would expect the performance penalty to lie in the other direction.  Recursive calls can lead to the construction of extra stack frames; the penalty for this varies.  Also, in some languages like Python (more correctly, in some implementations of some languages...), you can run into stack limits rather easily for tasks you might specify recursively, such as finding the maximum value in a tree data structure.  In these cases, you really want to stick with loops.</p>\n\n<p>Writing good recursive functions can reduce the performance penalty somewhat, assuming you have a compiler that optimizes tail recursions, etc.  (Also double check to make sure that the function really is tail recursive---it\'s one of those things that many people make mistakes on.)</p>\n\n<p>Apart from "edge" cases (high performance computing, very large recursion depth, etc.), it\'s preferable to adopt the approach that most clearly expresses your intent, is well-designed, and is maintainable.  Optimize only after identifying a need.</p>\n'}, {'answer_id': 72395, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 2, 'selected': False, 'text': '<p>it depends on "recursion depth".\nit depends on how much the function call overhead will influence the total execution time.</p>\n\n<p>For example, calculating the classical factorial in a recursive way is very inefficient due to:\n- risk of data overflowing\n- risk of stack overflowing\n- function call overhead occupy 80% of execution time</p>\n\n<p>while developing a min-max algorithm for position analysis in the game of chess that will analyze subsequent N moves can be implemented in recursion over the "analysis depth" (as I\'m doing ^_^)</p>\n'}, {'answer_id': 72469, 'author': 'Paul Osborne', 'author_id': 7049, 'author_profile': 'https://Stackoverflow.com/users/7049', 'pm_score': 9, 'selected': True, 'text': '<p>It is possible that recursion will be more expensive, depending on if the recursive function is <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="noreferrer">tail recursive</a> (the last line is recursive call).  Tail recursion <em>should</em> be recognized by the compiler and optimized to its iterative counterpart (while maintaining the concise, clear implementation you have in your code).</p>\n\n<p>I would write the algorithm in the way that makes the most sense and is the clearest for the poor sucker (be it yourself or someone else) that has to maintain the code in a few months or years.  If you run into performance issues, then profile your code, and then and only then look into optimizing by moving over to an iterative implementation.  You may want to look into <a href="http://en.wikipedia.org/wiki/Memoization" rel="noreferrer">memoization</a> and <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="noreferrer">dynamic programming</a>.</p>\n'}, {'answer_id': 72506, 'author': 'entzik', 'author_id': 12297, 'author_profile': 'https://Stackoverflow.com/users/12297', 'pm_score': 3, 'selected': False, 'text': "<p>Your performance deteriorates when using recursion because calling a method, in any language, implies a lot of preparation: the calling code posts a return address, call parameters, some other context information such as processor registers might be saved somewhere, and at return time the called method posts a return value which is then retrieved by the caller, and any context information that was previously saved will be restored. the performance diff between an iterative and a recursive approach lies in the time these operations take. </p>\n\n<p>From an implementation point of view, you really start noticing the difference when the time it takes to handle the calling context is comparable to the time it takes for your method to execute. If your recursive method takes longer to execute then the calling context management part, go the recursive way as the code is generally more readable and easy to understand and you won't notice the performance loss. Otherwise go iterative for efficiency reasons. </p>\n"}, {'answer_id': 72522, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I believe tail recursion in java is not currently optimized.  The details are sprinkled throughout <a href="http://lambda-the-ultimate.org/node/1333" rel="noreferrer">this</a> discussion on LtU and the associated links.  It <em>may</em> be a feature in the upcoming version 7, but apparently it presents certain difficulties when combined with Stack Inspection since certain frames would be missing.  Stack Inspection has been used to implement their fine-grained security model since Java 2.</p>\n\n<p><a href="http://lambda-the-ultimate.org/node/1333" rel="noreferrer">http://lambda-the-ultimate.org/node/1333</a></p>\n'}, {'answer_id': 72694, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 9, 'selected': False, 'text': '<p>Loops may achieve a performance gain for your program. Recursion may achieve a performance gain for your programmer. Choose which is more important in your situation!</p>\n'}, {'answer_id': 72803, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 1, 'selected': False, 'text': '<p>Mike is correct. Tail recursion is <em>not</em> optimized out by the Java compiler or the JVM. You will always get a stack overflow with something like this:</p>\n\n<pre><code>int count(int i) {\n  return i &gt;= 100000000 ? i : count(i+1);\n}\n</code></pre>\n'}, {'answer_id': 278563, 'author': 'Brad Gilbert', 'author_id': 1337, 'author_profile': 'https://Stackoverflow.com/users/1337', 'pm_score': 0, 'selected': False, 'text': '<p>As far as I know, Perl does not optimize tail-recursive calls, but you can fake it.</p>\n\n<pre><code>sub f{\n  my($l,$r) = @_;\n\n  if( $l &gt;= $r ){\n    return $l;\n  } else {\n\n    # return f( $l+1, $r );\n\n    @_ = ( $l+1, $r );\n    goto &amp;f;\n\n  }\n}\n</code></pre>\n\n<p>When first called it will allocate space on the stack. Then it will change its arguments, and restart the subroutine, without adding anything more to the stack. It will therefore pretend that it never called its self, changing it into an iterative process.</p>\n\n<p><em>Note that there is no "<code>my @_;</code>" or "<code>local @_;</code>", if you did it would no longer work.</em></p>\n'}, {'answer_id': 327256, 'author': 'Warrior', 'author_id': 40933, 'author_profile': 'https://Stackoverflow.com/users/40933', 'pm_score': 2, 'selected': False, 'text': '<p>Recursion and iteration depends on the business logic that you want to implement, though in most of the cases it can be used interchangeably. Most developers go for recursion because it is easier to understand.</p>\n'}, {'answer_id': 6463085, 'author': 'Felix', 'author_id': 773852, 'author_profile': 'https://Stackoverflow.com/users/773852', 'pm_score': 3, 'selected': False, 'text': "<p>There are many cases where it gives a much more elegant solution over the iterative method, the common example being traversal of a binary tree, so it isn't necessarily more difficult to maintain. In general, iterative versions are usually a bit faster (and during optimization may well replace a recursive version), but recursive versions are simpler to comprehend and implement correctly. </p>\n"}, {'answer_id': 6463107, 'author': 'Harikrishnan', 'author_id': 721597, 'author_profile': 'https://Stackoverflow.com/users/721597', 'pm_score': 3, 'selected': False, 'text': '<p>Recursion is very useful is some situations. For example consider the code for finding the factorial</p>\n\n\n\n<pre class="lang-c prettyprint-override"><code>int factorial ( int input )\n{\n  int x, fact = 1;\n  for ( x = input; x &gt; 1; x--)\n     fact *= x;\n  return fact;\n}\n</code></pre>\n\n<p>Now consider it by using the recursive function</p>\n\n<pre class="lang-c prettyprint-override"><code>int factorial ( int input )\n{\n  if (input == 0)\n  {\n     return 1;\n  }\n  return input * factorial(input - 1);\n}\n</code></pre>\n\n<p>By observing these two, we can see that recursion is easy to understand.\nBut if it is not used with care it can be so much error prone too. \nSuppose if we miss <code>if (input == 0)</code>, then the code will be executed for some time and ends with usually a stack overflow.</p>\n'}, {'answer_id': 6463113, 'author': 'Swift', 'author_id': 385913, 'author_profile': 'https://Stackoverflow.com/users/385913', 'pm_score': 6, 'selected': False, 'text': '<p>Comparing recursion to iteration is like comparing a phillips head screwdriver to a flat head screwdriver.  For the most part you <em>could</em> remove any phillips head screw with a flat head, but it would just be easier if you used the screwdriver designed for that screw right? </p>\n\n<p>Some algorithms just lend themselves to recursion because of the way they are designed (Fibonacci sequences, traversing a tree like structure, etc.).  Recursion makes the algorithm more succinct and easier to understand (therefore shareable and reusable).</p>\n\n<p>Also, some recursive algorithms use "Lazy Evaluation" which makes them more efficient than their iterative brothers. This means that they only do the expensive calculations at the time they are needed rather than each time the loop runs.</p>\n\n<p>That should be enough to get you started. I\'ll dig up some articles and examples for you too.</p>\n\n<p><strong><em>Link 1:</em> Haskel vs PHP (Recursion vs Iteration)</strong></p>\n\n<p>Here is an example where the programmer had to process a large data set using PHP.  He shows how easy it would have been to deal with in Haskel using recursion, but since PHP had no easy way to accomplish the same method, he was forced to use iteration to get the result.</p>\n\n<blockquote>\n  <p><a href="http://blog.webspecies.co.uk/2011-05-31/lazy-evaluation-with-php.html" rel="noreferrer">http://blog.webspecies.co.uk/2011-05-31/lazy-evaluation-with-php.html</a></p>\n</blockquote>\n\n<p><strong><em>Link 2:</em> Mastering Recursion</strong></p>\n\n<p>Most of recursion\'s bad reputation comes from the high costs and inefficiency in imperative languages.  The author of this article talks about how to optimize recursive algorithms to make them faster and more efficient.  He also goes over how to convert a traditional loop into a recursive function and the benefits of using tail-end recursion.  His closing words really summed up some of my key points I think: </p>\n\n<blockquote>\n  <p>"recursive programming gives the programmer a better way of organizing\n  code in a way that is both maintainable and logically consistent."</p>\n  \n  <p><a href="https://developer.ibm.com/articles/l-recurs/" rel="noreferrer">https://developer.ibm.com/articles/l-recurs/</a></p>\n</blockquote>\n\n<p><strong><em>Link 3:</em> Is recursion ever faster than looping? (Answer)</strong></p>\n\n<p>Here is a link to an answer for a stackoverflow question that is similar to yours. The author points out that a lot of the benchmarks associated with either recursing or looping are <strong>very</strong> language specific.  Imperative languages are typically faster using a loop and slower with recursion and vice-versa for functional languages.  I guess the main point to take from this link is that it is very difficult to answer the question in a language agnostic / situation blind sense.</p>\n\n<blockquote>\n  <p><a href="https://stackoverflow.com/questions/2651112/is-recursion-ever-faster-than-looping/2651200#2651200">Is recursion ever faster than looping?</a></p>\n</blockquote>\n'}, {'answer_id': 6463175, 'author': 'Nickz', 'author_id': 332395, 'author_profile': 'https://Stackoverflow.com/users/332395', 'pm_score': 2, 'selected': False, 'text': '<p>Recursion? Where do I start, wiki will tell you “it’s the process of repeating items in a self-similar way"</p>\n\n<p>Back in day when I was doing C, C++ recursion was a god send, stuff like "Tail recursion". You\'ll also find many sorting algorithms use recursion. Quick sort example: <a href="http://alienryderflex.com/quicksort/" rel="nofollow noreferrer">http://alienryderflex.com/quicksort/</a></p>\n\n<p>Recursion is like any other algorithm useful for a specific problem. Perhaps you mightn\'t find a use straight away or often but there will be problem you’ll be glad it’s available. </p>\n'}, {'answer_id': 6463185, 'author': 'Joe Cheng', 'author_id': 139922, 'author_profile': 'https://Stackoverflow.com/users/139922', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re just iterating over a list, then sure, iterate away.</p>\n\n<p>A couple of other answers have mentioned (depth-first) tree traversal. It really is such a great example, because it\'s a very common thing to do to a very common data structure. Recursion is extremely intuitive for this problem.</p>\n\n<p>Check out the "find" methods here:\n<a href="http://penguin.ewu.edu/cscd300/Topic/BSTintro/index.html" rel="nofollow">http://penguin.ewu.edu/cscd300/Topic/BSTintro/index.html</a></p>\n'}, {'answer_id': 6463304, 'author': 'Ben', 'author_id': 751751, 'author_profile': 'https://Stackoverflow.com/users/751751', 'pm_score': 3, 'selected': False, 'text': '<p>Recursion is better than iteration for problems that can be broken down into <strong>multiple</strong>, smaller pieces.</p>\n\n<p>For example, to make a recursive Fibonnaci algorithm, you break down fib(n) into fib(n-1) and fib(n-2) and compute both parts. Iteration only allows you to repeat a single function over and over again.</p>\n\n<p>However, Fibonacci is actually a broken example and I think iteration is actually more efficient. Notice that fib(n) = fib(n-1) + fib(n-2) and fib(n-1) = fib(n-2) + fib(n-3). fib(n-1) gets calculated twice!</p>\n\n<p>A better example is a recursive algorithm for a tree. The problem of analyzing the parent node can be broken down into <strong>multiple</strong> smaller problems of analyzing each child node. Unlike the Fibonacci example, the smaller problems are independent of each other.</p>\n\n<p>So yeah - recursion is better than iteration for problems that can be broken down into multiple, smaller, independent, similar problems.</p>\n'}, {'answer_id': 6466595, 'author': 'SK-logic', 'author_id': 293147, 'author_profile': 'https://Stackoverflow.com/users/293147', 'pm_score': 2, 'selected': False, 'text': '<p>Recursion is more simple (and thus - more fundamental) than any possible definition of an iteration. You can define a Turing-complete system with only a <a href="http://en.wikipedia.org/wiki/SK_calculus" rel="nofollow">pair of combinators</a> (yes, even a recursion itself is a derivative notion in such a system). <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="nofollow">Lambda</a> calculus is an equally powerful fundamental system, featuring recursive functions. But if you want to define an iteration properly, you\'d need much more primitives to start with.</p>\n\n<p>As for the code - no, recursive code is in fact much easier to understand and to maintain than a purely iterative one, since most data structures are recursive. Of course, in order to get it right one would need a language with a support for high order functions and closures, at least - to get all the standard combinators and iterators in a neat way. In C++, of course, complicated recursive solutions can look a bit ugly, unless you\'re a hardcore user of <a href="http://www.cc.gatech.edu/~yannis/fc++/" rel="nofollow">FC++</a> and alike.</p>\n'}, {'answer_id': 13775120, 'author': 'Nikunj Banka', 'author_id': 1737817, 'author_profile': 'https://Stackoverflow.com/users/1737817', 'pm_score': 3, 'selected': False, 'text': '<p>In many cases recursion is faster because of caching, which improves performance. For example, here is an iterative version of merge sort using the traditional merge routine. It will run slower than the recursive implementation because of caching improved performances.</p>\n\n<h1>Iterative implementation</h1>\n\n<pre class="lang-java prettyprint-override"><code>public static void sort(Comparable[] a)\n{\n    int N = a.length;\n    aux = new Comparable[N];\n    for (int sz = 1; sz &lt; N; sz = sz+sz)\n        for (int lo = 0; lo &lt; N-sz; lo += sz+sz)\n            merge(a, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));\n}\n</code></pre>\n\n<h1>Recursive implementation</h1>\n\n<pre class="lang-java prettyprint-override"><code>private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi)\n{\n    if (hi &lt;= lo) return;\n    int mid = lo + (hi - lo) / 2;\n    sort(a, aux, lo, mid);\n    sort(a, aux, mid+1, hi);\n    merge(a, aux, lo, mid, hi);\n}\n</code></pre>\n\n<p>PS - this is what was told by Professor Kevin Wayne (Princeton University)  on the course on algorithms presented on Coursera.</p>\n'}, {'answer_id': 15581513, 'author': 'nomen', 'author_id': 738762, 'author_profile': 'https://Stackoverflow.com/users/738762', 'pm_score': -1, 'selected': False, 'text': '<p>I\'m going to answer your question by designing a Haskell data structure by "induction", which is a sort of "dual" to recursion.  And then I will show how this duality leads to nice things.</p>\n\n<p>We introduce a type for a simple tree:</p>\n\n<pre><code>data Tree a = Branch (Tree a) (Tree a)\n            | Leaf a\n            deriving (Eq)\n</code></pre>\n\n<p>We can read this definition as saying "A tree is a Branch (which contains two trees) or is a leaf (which contains a data value)".  So the leaf is a sort of minimal case.  If a tree isn\'t a leaf, then it must be a compound tree containing two trees.  These are the only cases.</p>\n\n<p>Let\'s make a tree:</p>\n\n<pre><code>example :: Tree Int\nexample = Branch (Leaf 1) \n                 (Branch (Leaf 2) \n                         (Leaf 3))\n</code></pre>\n\n<p>Now, let\'s suppose we want to add 1 to each value in the tree.  We can do this by calling:</p>\n\n<pre><code>addOne :: Tree Int -&gt; Tree Int\naddOne (Branch a b) = Branch (addOne a) (addOne b)\naddOne (Leaf a)     = Leaf (a + 1)\n</code></pre>\n\n<p>First, notice that this is in fact a recursive definition.  It takes the data constructors Branch and Leaf as cases (and since Leaf is minimal and these are the only possible cases), we are sure that the function will terminate.</p>\n\n<p>What would it take to write addOne in an iterative style?  What will looping into an arbitrary number of branches look like?</p>\n\n<p>Also, this kind of recursion can often be factored out, in terms of a "functor".  We can make Trees into Functors by defining:</p>\n\n<pre><code>instance Functor Tree where fmap f (Leaf a)     = Leaf (f a)\n                            fmap f (Branch a b) = Branch (fmap f a) (fmap f b)\n</code></pre>\n\n<p>and defining:</p>\n\n<pre><code>addOne\' = fmap (+1)\n</code></pre>\n\n<p>We can factor out other recursion schemes, such as the catamorphism (or fold) for an algebraic data type.  Using a catamorphism, we can write:</p>\n\n<pre><code>addOne\'\' = cata go where\n           go (Leaf a) = Leaf (a + 1)\n           go (Branch a b) = Branch a b\n</code></pre>\n'}, {'answer_id': 16128580, 'author': 'ccpizza', 'author_id': 191246, 'author_profile': 'https://Stackoverflow.com/users/191246', 'pm_score': 1, 'selected': False, 'text': '<p>If the iterations are atomic and orders of magnitude more expensive than pushing a new stack frame <em>and</em> creating a new thread <em>and</em> you have multiple cores <em>and</em> your runtime environment can use all of them, then a recursive approach could yield a huge performance boost when combined with multithreading. If the average number of iterations is not predictable then it might be a good idea to use a thread pool which will control thread allocation and prevent your process from creating too many threads and hogging the system.</p>\n\n<p>For example, in some languages, there are recursive multithreaded merge sort implementations.</p>\n\n<p>But again, multithreading can be used with looping rather than recursion, so how well this combination will work depends on more factors including the OS and its thread allocation mechanism.</p>\n'}, {'answer_id': 21431707, 'author': 'Grigori A.', 'author_id': 1338803, 'author_profile': 'https://Stackoverflow.com/users/1338803', 'pm_score': 1, 'selected': False, 'text': '<p>You have to keep in mind that utilizing too deep recursion you will run into Stack Overflow, depending on allowed stack size. To prevent this make sure to provide some base case which ends you recursion.</p>\n'}, {'answer_id': 32613300, 'author': 'AlphaG33k', 'author_id': 4937914, 'author_profile': 'https://Stackoverflow.com/users/4937914', 'pm_score': 1, 'selected': False, 'text': '<p>Using just Chrome 45.0.2454.85 m, recursion seems to be a nice amount faster. </p>\n\n<p>Here is the code:</p>\n\n<pre><code>(function recursionVsForLoop(global) {\n    "use strict";\n\n    // Perf test\n    function perfTest() {}\n\n    perfTest.prototype.do = function(ns, fn) {\n        console.time(ns);\n        fn();\n        console.timeEnd(ns);\n    };\n\n    // Recursion method\n    (function recur() {\n        var count = 0;\n        global.recurFn = function recurFn(fn, cycles) {\n            fn();\n            count = count + 1;\n            if (count !== cycles) recurFn(fn, cycles);\n        };\n    })();\n\n    // Looped method\n    function loopFn(fn, cycles) {\n        for (var i = 0; i &lt; cycles; i++) {\n            fn();\n        }\n    }\n\n    // Tests\n    var curTest = new perfTest(),\n        testsToRun = 100;\n\n    curTest.do(\'recursion\', function() {\n        recurFn(function() {\n            console.log(\'a recur run.\');\n        }, testsToRun);\n    });\n\n    curTest.do(\'loop\', function() {\n        loopFn(function() {\n            console.log(\'a loop run.\');\n        }, testsToRun);\n    });\n\n})(window);\n</code></pre>\n\n<p><strong>RESULTS</strong></p>\n\n<p>// 100 runs using standard for loop</p>\n\n<p>100x for loop run.\nTime to complete: <strong>7.683ms</strong></p>\n\n<p>// 100 runs using functional recursive approach w/ tail recursion</p>\n\n<p>100x recursion run.\nTime to complete: <strong>4.841ms</strong></p>\n\n<p><strong>In the screenshot below, recursion wins again by a bigger margin when run at 300 cycles per test</strong></p>\n\n<p><a href="https://i.stack.imgur.com/dQemM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dQemM.png" alt="Recursion wins again!"></a></p>\n'}, {'answer_id': 33048493, 'author': 'Titas Chanda', 'author_id': 5395216, 'author_profile': 'https://Stackoverflow.com/users/5395216', 'pm_score': 2, 'selected': False, 'text': '<p>In C++ if the recursive function is a templated one, then the compiler has more chance to optimize it, as all the type deduction and function instantiations will occur in compile time. Modern compilers can also inline the function if possible. So if one uses optimization flags like <code>-O3</code> or <code>-O2</code> in <code>g++</code>, then recursions may have the chance to be faster than iterations. In iterative codes, the compiler gets less chance to optimize it, as it is already in the more or less optimal state (if written well enough).</p>\n\n<p>In my case, I was trying to implement matrix exponentiation by squaring using Armadillo matrix objects, in both recursive and iterative way. The algorithm can be found here... <a href="https://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Exponentiation_by_squaring</a>.\nMy functions were templated and I have calculated <code>1,000,000</code> <code>12x12</code> matrices raised to the power <code>10</code>. I got the following result:</p>\n\n<pre><code>iterative + optimisation flag -O3 -&gt; 2.79.. sec\nrecursive + optimisation flag -O3 -&gt; 1.32.. sec\n\niterative + No-optimisation flag  -&gt; 2.83.. sec\nrecursive + No-optimisation flag  -&gt; 4.15.. sec\n</code></pre>\n\n<p>These results have been obtained using gcc-4.8 with c++11 flag (<code>-std=c++11</code>) and Armadillo 6.1 with Intel mkl. Intel compiler also shows similar results.</p>\n'}, {'answer_id': 44327561, 'author': 'Varunnuevothoughts', 'author_id': 8012261, 'author_profile': 'https://Stackoverflow.com/users/8012261', 'pm_score': 2, 'selected': False, 'text': "<p>Recursion has a disadvantage that the algorithm that you write using recursion has O(n) space complexity.\nWhile iterative aproach have a space complexity of O(1).This is the advantange of using iteration over recursion.\nThen why do we use recursion? </p>\n\n<p>See below.</p>\n\n<p>Sometimes it is easier to write an algorithm using recursion while it's slightly tougher to write the same algorithm using iteration.In this case if you opt to follow the iteration approach you would have to handle stack yourself.</p>\n"}, {'answer_id': 47574991, 'author': 'F13n0', 'author_id': 9034192, 'author_profile': 'https://Stackoverflow.com/users/9034192', 'pm_score': -1, 'selected': False, 'text': "<p>Stack overflow will only occur if you're programming in a language that doesn't have in built memory management.... Otherwise, make sure you have something in your function (or a function call, STDLbs, etc). Without recursion it would simply not be possible to have things like... Google or SQL, or any place one must efficiently sort through large data structures (classes) or databases. </p>\n\n<p>Recursion is the way to go if you want to iterate through files, pretty sure that's how 'find * | ?grep *' works. Kinda dual recursion, especially with the pipe (but don't do a bunch of syscalls like so many like to do if it's anything you're going to put out there for others to use).</p>\n\n<p>Higher level languages and even clang/cpp may implement it the same in the background.</p>\n"}, {'answer_id': 59900284, 'author': 'Vladimir Nabokov', 'author_id': 2285111, 'author_profile': 'https://Stackoverflow.com/users/2285111', 'pm_score': 1, 'selected': False, 'text': '<p>I found another differences between those approaches.\nIt looks simple and unimportant, but it has a very important role while you prepare for interviews and this subject arises, so look closely.</p>\n\n<p>In short: \n1) iterative post-order traversal is not easy - that makes DFT more complex\n2) cycles check easier with recursion</p>\n\n<p>Details:</p>\n\n<p>In the recursive case, it is easy to create pre and post traversals:</p>\n\n<p>Imagine a pretty standard question: "print all tasks that should be executed to execute the task 5, when tasks depend on other tasks"</p>\n\n<p>Example:</p>\n\n<pre><code>    //key-task, value-list of tasks the key task depends on\n    //"adjacency map":\n    Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap = new HashMap&lt;&gt;();\n    tasksMap.put(0, new ArrayList&lt;&gt;());\n    tasksMap.put(1, new ArrayList&lt;&gt;());\n\n    List&lt;Integer&gt; t2 = new ArrayList&lt;&gt;();\n    t2.add(0);\n    t2.add(1);\n    tasksMap.put(2, t2);\n\n    List&lt;Integer&gt; t3 = new ArrayList&lt;&gt;();\n    t3.add(2);\n    t3.add(10);\n    tasksMap.put(3, t3);\n\n    List&lt;Integer&gt; t4 = new ArrayList&lt;&gt;();\n    t4.add(3);\n    tasksMap.put(4, t4);\n\n    List&lt;Integer&gt; t5 = new ArrayList&lt;&gt;();\n    t5.add(3);\n    tasksMap.put(5, t5);\n\n    tasksMap.put(6, new ArrayList&lt;&gt;());\n    tasksMap.put(7, new ArrayList&lt;&gt;());\n\n    List&lt;Integer&gt; t8 = new ArrayList&lt;&gt;();\n    t8.add(5);\n    tasksMap.put(8, t8);\n\n    List&lt;Integer&gt; t9 = new ArrayList&lt;&gt;();\n    t9.add(4);\n    tasksMap.put(9, t9);\n\n    tasksMap.put(10, new ArrayList&lt;&gt;());\n\n    //task to analyze:\n    int task = 5;\n\n\n    List&lt;Integer&gt; res11 = getTasksInOrderDftReqPostOrder(tasksMap, task);\n    System.out.println(res11);**//note, no reverse required**\n\n    List&lt;Integer&gt; res12 = getTasksInOrderDftReqPreOrder(tasksMap, task);\n    Collections.reverse(res12);//note reverse!\n    System.out.println(res12);\n\n    private static List&lt;Integer&gt; getTasksInOrderDftReqPreOrder(Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap, int task) {\n         List&lt;Integer&gt; result = new ArrayList&lt;&gt;();\n         Set&lt;Integer&gt; visited = new HashSet&lt;&gt;();\n         reqPreOrder(tasksMap,task,result, visited);\n         return result;\n    }\n\nprivate static void reqPreOrder(Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap, int task, List&lt;Integer&gt; result, Set&lt;Integer&gt; visited) {\n\n    if(!visited.contains(task)) {\n        visited.add(task);\n        result.add(task);//pre order!\n        List&lt;Integer&gt; children = tasksMap.get(task);\n        if (children != null &amp;&amp; children.size() &gt; 0) {\n            for (Integer child : children) {\n                reqPreOrder(tasksMap,child,result, visited);\n            }\n        }\n    }\n}\n\nprivate static List&lt;Integer&gt; getTasksInOrderDftReqPostOrder(Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap, int task) {\n    List&lt;Integer&gt; result = new ArrayList&lt;&gt;();\n    Set&lt;Integer&gt; visited = new HashSet&lt;&gt;();\n    reqPostOrder(tasksMap,task,result, visited);\n    return result;\n}\n\nprivate static void reqPostOrder(Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap, int task, List&lt;Integer&gt; result, Set&lt;Integer&gt; visited) {\n    if(!visited.contains(task)) {\n        visited.add(task);\n        List&lt;Integer&gt; children = tasksMap.get(task);\n        if (children != null &amp;&amp; children.size() &gt; 0) {\n            for (Integer child : children) {\n                reqPostOrder(tasksMap,child,result, visited);\n            }\n        }\n        result.add(task);//post order!\n    }\n}\n</code></pre>\n\n<p>Note that the recursive post-order-traversal does not require a subsequent reversal of the result. Children printed first and your task in the question printed last. Everything is fine. You can do a recursive pre-order-traversal (also shown above) and that one will require a reversal of the result list. </p>\n\n<p><strong>Not that simple with iterative approach!</strong> In iterative (one stack) approach you can only do a pre-ordering-traversal, so you obliged to reverse the result array at the end:</p>\n\n<pre><code>    List&lt;Integer&gt; res1 = getTasksInOrderDftStack(tasksMap, task);\n    Collections.reverse(res1);//note reverse!\n    System.out.println(res1);\n\n    private static List&lt;Integer&gt; getTasksInOrderDftStack(Map&lt;Integer, List&lt;Integer&gt;&gt; tasksMap, int task) {\n    List&lt;Integer&gt; result = new ArrayList&lt;&gt;();\n    Set&lt;Integer&gt; visited = new HashSet&lt;&gt;();\n    Stack&lt;Integer&gt; st = new Stack&lt;&gt;();\n\n\n    st.add(task);\n    visited.add(task);\n\n    while(!st.isEmpty()){\n        Integer node = st.pop();\n        List&lt;Integer&gt; children = tasksMap.get(node);\n        result.add(node);\n        if(children!=null &amp;&amp; children.size() &gt; 0){\n            for(Integer child:children){\n                if(!visited.contains(child)){\n                    st.add(child);\n                    visited.add(child);\n                }\n            }\n        }\n        //If you put it here - it does not matter - it is anyway a pre-order\n        //result.add(node);\n    }\n    return result;\n}\n</code></pre>\n\n<p>Looks simple, no?</p>\n\n<p>But it is a trap in some interviews.</p>\n\n<p>It means the following: with the recursive approach, you can implement Depth First Traversal and then select what order you need pre or post(simply by changing the location of the "print", in our case of the "adding to the result list"). With the iterative (one stack) approach you can <strong>easily</strong> do only pre-order traversal and so in the situation when children need be printed first(pretty much all situations when you need start print from the bottom nodes, going upwards) - you are in the trouble. If you have that trouble you can reverse later, but it will be an addition to your algorithm. And if an interviewer is looking at his watch it may be a problem for you. There are complex ways to do an iterative post-order traversal, they exist, but they are <strong>not simple</strong>. Example:<a href="https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/</a></p>\n\n<p>Thus, the bottom line: I would use recursion during interviews, it is simpler to manage and to explain. You have an easy way to go from pre to post-order traversal in any urgent case. With iterative you are not that flexible.</p>\n\n<p>I would use recursion and then tell: "Ok, but iterative can provide me more direct control on used memory, I can easily measure the stack size and disallow some dangerous overflow.."</p>\n\n<p>Another plus of recursion  - it is simpler to avoid / notice cycles in a graph.</p>\n\n<p>Example (preudocode):</p>\n\n<pre><code>dft(n){\n    mark(n)\n    for(child: n.children){\n        if(marked(child)) \n            explode - cycle found!!!\n        dft(child)\n    }\n    unmark(n)\n}\n</code></pre>\n'}, {'answer_id': 60530502, 'author': 'nonopolarity', 'author_id': 325418, 'author_profile': 'https://Stackoverflow.com/users/325418', 'pm_score': 1, 'selected': False, 'text': "<p>It may be fun to write it as recursion, or as a practice.</p>\n<p>However, if the code is to be used in production, you need to consider the possibility of stack overflow.</p>\n<p>Tail recursion optimization can eliminate stack overflow, but do you want to go through the trouble of making it so, and you need to know you can count on it having the optimization in your environment.</p>\n<h2>Every time the algorithm recurses, how much is the data size or <code>n</code> reduced by?</h2>\n<p>If you are reducing the size of data or <code>n</code> by half every time you recurse, then in general you don't need to worry about stack overflow. Say, if it needs to be 4,000 level deep or 10,000 level deep for the program to stack overflow, then your data size need to be roughly 2<sup>4000</sup> for your program to stack overflow. To put that into perspective, a biggest storage device recently can hold 2<sup>61</sup> bytes, and if you have  2<sup>61</sup> of such devices, you are only dealing with 2<sup>122</sup> data size. If you are looking at all the atoms in the universe, it is estimated that it may be less than 2<sup>84</sup>. If you need to deal with all the data in the universe and their states for every millisecond since the birth of the universe estimated to be 14 billion years ago, it may only be 2<sup>153</sup>. So if your program can handle 2<sup>4000</sup> units of data or <code>n</code>, you can handle all data in the universe and the program will not stack overflow. If you don't need to deal with numbers that are as big as 2<sup>4000</sup> (a 4000-bit integer), then in general you don't need to worry about stack overflow.</p>\n<p>However, if you reduce the size of data or <code>n</code> by a constant amount every time you recurse, then you can run into stack overflow when <code>n</code> becomes merely <code>20000</code>.  That is, the program runs well when <code>n</code> is <code>1000</code>, and you think the program is good, and then the program stack overflows when some time in the future, when <code>n</code> is <code>5000</code> or <code>20000</code>.</p>\n<p>So if you have a possibility of stack overflow, try to make it an iterative solution.</p>\n"}, {'answer_id': 74271649, 'author': 'chen', 'author_id': 20064859, 'author_profile': 'https://Stackoverflow.com/users/20064859', 'pm_score': 0, 'selected': False, 'text': "<p>&quot;Is there a performance hit if we use a loop instead of\nrecursion or vice versa in algorithms where both can serve the same purpose?&quot;</p>\n<p>Usually yes if you are writing in a imperative language iteration will run faster than recursion, the performance hit is minimized in problems where the iterative solution requires manipulating Stacks and popping items off of a stack due to the recursive nature of the problem. There are a lot of times where the recursive implementation is much easier to read because the code is much shorter,\nso you do want to consider maintainability. Especailly in cases where the problem has a recursive nature. So take for example:</p>\n<p>The recursive implementation of Tower of Hanoi:</p>\n<pre><code>def TowerOfHanoi(n , source, destination, auxiliary):\n    if n==1:\n        print (&quot;Move disk 1 from source&quot;,source,&quot;to destination&quot;,destination)\n        return\n    TowerOfHanoi(n-1, source, auxiliary, destination)\n    print (&quot;Move disk&quot;,n,&quot;from source&quot;,source,&quot;to destination&quot;,destination)\n    TowerOfHanoi(n-1, auxiliary, destination, source)\n</code></pre>\n<p>Fairly short and pretty easy to read. Compare this with its Counterpart iterative TowerOfHanoi:</p>\n<pre><code># Python3 program for iterative Tower of Hanoi\nimport sys\n \n# A structure to represent a stack\nclass Stack:\n    # Constructor to set the data of\n    # the newly created tree node\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.top = -1\n        self.array = [0]*capacity\n \n# function to create a stack of given capacity.\ndef createStack(capacity):\n    stack = Stack(capacity)\n    return stack\n  \n# Stack is full when top is equal to the last index\ndef isFull(stack):\n    return (stack.top == (stack.capacity - 1))\n   \n# Stack is empty when top is equal to -1\ndef isEmpty(stack):\n    return (stack.top == -1)\n   \n# Function to add an item to stack.\n# It increases top by 1\ndef push(stack, item):\n    if(isFull(stack)):\n        return\n    stack.top+=1\n    stack.array[stack.top] = item\n   \n# Function to remove an item from stack.\n# It decreases top by 1\ndef Pop(stack):\n    if(isEmpty(stack)):\n        return -sys.maxsize\n    Top = stack.top\n    stack.top-=1\n    return stack.array[Top]\n   \n# Function to implement legal\n# movement between two poles\ndef moveDisksBetweenTwoPoles(src, dest, s, d):\n    pole1TopDisk = Pop(src)\n    pole2TopDisk = Pop(dest)\n \n    # When pole 1 is empty\n    if (pole1TopDisk == -sys.maxsize):\n        push(src, pole2TopDisk)\n        moveDisk(d, s, pole2TopDisk)\n       \n    # When pole2 pole is empty\n    else if (pole2TopDisk == -sys.maxsize):\n        push(dest, pole1TopDisk)\n        moveDisk(s, d, pole1TopDisk)\n       \n    # When top disk of pole1 &gt; top disk of pole2\n    else if (pole1TopDisk &gt; pole2TopDisk):\n        push(src, pole1TopDisk)\n        push(src, pole2TopDisk)\n        moveDisk(d, s, pole2TopDisk)\n       \n    # When top disk of pole1 &lt; top disk of pole2\n    else:\n        push(dest, pole2TopDisk)\n        push(dest, pole1TopDisk)\n        moveDisk(s, d, pole1TopDisk)\n   \n# Function to show the movement of disks\ndef moveDisk(fromPeg, toPeg, disk):\n    print(&quot;Move the disk&quot;, disk, &quot;from '&quot;, fromPeg, &quot;' to '&quot;, toPeg, &quot;'&quot;)\n   \n# Function to implement TOH puzzle\ndef tohIterative(num_of_disks, src, aux, dest):\n    s, d, a = 'S', 'D', 'A'\n   \n    # If number of disks is even, then interchange\n    # destination pole and auxiliary pole\n    if (num_of_disks % 2 == 0):\n        temp = d\n        d = a\n        a = temp\n    total_num_of_moves = int(pow(2, num_of_disks) - 1)\n   \n    # Larger disks will be pushed first\n    for i in range(num_of_disks, 0, -1):\n        push(src, i)\n   \n    for i in range(1, total_num_of_moves + 1):\n        if (i % 3 == 1):\n            moveDisksBetweenTwoPoles(src, dest, s, d)\n   \n        else if (i % 3 == 2):\n            moveDisksBetweenTwoPoles(src, aux, s, a)\n   \n        else if (i % 3 == 0):\n            moveDisksBetweenTwoPoles(aux, dest, a, d)\n \n# Input: number of disks\nnum_of_disks = 3\n \n# Create three stacks of size 'num_of_disks'\n# to hold the disks\nsrc = createStack(num_of_disks)\ndest = createStack(num_of_disks)\naux = createStack(num_of_disks)\n \ntohIterative(num_of_disks, src, aux, dest)\n</code></pre>\n<p>Now the first one is way easier to read because suprise suprise shorter code is usually easier to understand than code that is 10 times longer. Sometimes you want to ask yourself is the extra performance gain really worth it? The amount of hours wasted debugging the code. Is the iterative TowerOfHanoi faster than the Recursive TowerOfHanoi? Probably, but not by a big margin. Would I like to program Recursive problems like TowerOfHanoi using iteration? Hell no. Next we have another recursive function the Ackermann function:\nUsing recursion:</p>\n<pre><code>    if m == 0:\n        # BASE CASE\n        return n + 1\n    elif m &gt; 0 and n == 0:\n        # RECURSIVE CASE\n        return ackermann(m - 1, 1)\n    elif m &gt; 0 and n &gt; 0:\n        # RECURSIVE CASE\n        return ackermann(m - 1, ackermann(m, n - 1))\n</code></pre>\n<p>Using Iteration:</p>\n<pre><code>callStack = [{'m': 2, 'n': 3, 'indentation': 0, 'instrPtr': 'start'}]\nreturnValue = None\n\nwhile len(callStack) != 0:\n    m = callStack[-1]['m']\n    n = callStack[-1]['n']\n    indentation = callStack[-1]['indentation']\n    instrPtr = callStack[-1]['instrPtr']\n\n    if instrPtr == 'start':\n        print('%sackermann(%s, %s)' % (' ' * indentation, m, n))\n\n        if m == 0:\n            # BASE CASE\n            returnValue = n + 1\n            callStack.pop()\n            continue\n        elif m &gt; 0 and n == 0:\n            # RECURSIVE CASE\n            callStack[-1]['instrPtr'] = 'after first recursive case'\n            callStack.append({'m': m - 1, 'n': 1, 'indentation': indentation + 1, 'instrPtr': 'start'})\n            continue\n        elif m &gt; 0 and n &gt; 0:\n            # RECURSIVE CASE\n            callStack[-1]['instrPtr'] = 'after second recursive case, inner call'\n            callStack.append({'m': m, 'n': n - 1, 'indentation': indentation + 1, 'instrPtr': 'start'})\n            continue\n    elif instrPtr == 'after first recursive case':\n        returnValue = returnValue\n        callStack.pop()\n        continue\n    elif instrPtr == 'after second recursive case, inner call':\n        callStack[-1]['innerCallResult'] = returnValue\n        callStack[-1]['instrPtr'] = 'after second recursive case, outer call'\n        callStack.append({'m': m - 1, 'n': returnValue, 'indentation': indentation + 1, 'instrPtr': 'start'})\n        continue\n    elif instrPtr == 'after second recursive case, outer call':\n        returnValue = returnValue\n        callStack.pop()\n        continue\nprint(returnValue)\n</code></pre>\n<p>And once again I will argue that the recursive implementation is much easier to understand. So my conclusion is use recursion if the problem by nature is recursive and requires manipulating items in a stack.</p>\n"}]
['https://Stackoverflow.com/questions/72209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11193/']