Is recursion faster than while loop python?
No, Iteration will always be faster than Recursion. (in a Von Neumann Architecture) Explanation:If you build the minimum operations of a generic computer from scratch, "Iteration" comes first as a building block and is less resource intensive than "recursion", ergo is faster. Building a pseudo-computing-machine from scratch:Question yourself: What do you need to compute a value, i.e. to follow an algorithm and reach a result? We will establish a hierarchy of concepts, starting from scratch and defining in first place the basic, core concepts, then build second level concepts with those, and so on.
... having reached recursion we stop here. Conclusion:In a Von Neumann Architecture, clearly "Iteration" is a simpler/basic concept than “Recursion". We have a form of "Iteration" at level 7, while "Recursion" is at level 14 of the concepts hierarchy. Iteration will always be faster in machine code because it implies less instructions therefore less CPU cycles. Which one is "better"?
Advice: use the best tool for the job, but understand the inner workings of each tool in order to choose wisely. Finally, note that you have plenty of opportunities to use recursion. You have Recursive Data Structures everywhere, you’re looking at one now: parts of the DOM supporting what you are reading are a RDS, a JSON expression is a RDS, the hierarchical file system in your computer is a RDS, i.e: you have a root directory, containing files and directories, every directory containing files and directories, every one of those directories containing files and directories... Is recursion fast in Python?Recursive method calls in Python cause a new stack frame allocation for every call. If you can iterate over a list instead then you avoid this allocation and will see a tremendous speed increase. The code below runs around 4x faster as a loop than as a recursive method.
Why loops are faster than recursion?The reason that loops are faster than recursion is easy. A loop looks like this in assembly. A single conditional jump and some bookkeeping for the loop counter. It's a lot more complex and you get at least 3 jumps (1 test to see if were done, one call and one return).
Are recursive functions faster than iteration Python?Recursion vs Iteration
Since Python does not store anything about previous iteration steps, iteration is quite faster and memory-efficient than recursion.
Does recursion increase speed?If your algorithm is naturally recursive, torturing it into a loop won't make it faster. If describing it as a loop makes sense, then making it recursive probably won't speed it up (or make it any slower, usually).
|