Tuesday, 3 December 2013

iteration vs recursion

In my previous posts. i already discussed recursion. Here, i take a further insight on recursion.
  • Iterative functions are typically faster than their recursive counterparts. So, if speed is an issue, you would normally use iteration.
  • If the stack limit is too constraining then you will prefer iteration over recursion.
  • Some procedures are very naturally programmed recursively, and all but unmanageable iteratively. Here, then, the choice is clear.
Typically, iteration is used for less complex problems, It depends on the complexity of the problem when it comes to deciding whether to use recursion or iteration. Recursion can be good or not, for example,  when dealing with easy ones, it is more efficient to use for loop rather than always use recursion.



Iteration is significantly cheaper than recursion. You will actually get an error ( RuntimeError: maximum recursion depth exceeded ) indicating that you exceeded maximum recursion depth if your function recurses too far.

This isn't specific to Python by any means. Recursion in most languages has a bit more overhead than iteration, since you have to make another function call every time and allocate a new stack frame.

Of course, there's nothing "wrong" with using recursion. Many algorithms can be expressed much more elegantly recursively than iteratively. However, if efficiency is a concern on any level, iteration is definitely the way to go.

No comments:

Post a Comment