Computer Science
Why are recursive functions considered slower than their iterative counterparts?
Python Functions
1 Like
Answer
When a loop is executed repeatedly, it uses the same memory locations for variables and repeats the same unit of code. On the other hand, recursion allocates fresh memory space for each recursive call, avoiding the repetition of code and the reuse of memory locations for variables. Due to stack manipulation and the allocation of additional memory space, recursive functions often run slower and consume more memory than their iterative counterparts.
Answered By
2 Likes
Related Questions
Is it necessary to have a base case in a recursive function? Why/Why not?
Identify the base case(s) in the following recursive function:
def function1(n): if n == 0: return 5 elif n == 1: return 8 elif n > 8 : return function1(n-1) + function1(n-2) else: return -1
Compare and contrast the use of iteration and recursion in terms of memory space and speed.
Predict the output of the following code.
def code(n): if n == 0: print ( 'Finally' ) else: print (n) code (3) code (15)