- 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.
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.
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