I compared the runtimes of a loop and a recursion, finding out, that the loop is way faster, while not having the problem of running into a RecursionError. Why is it, that loops are so much faster?
def factorial(n):
if n == 0:
return n
else:
return n + factorial(n-1)
%%timeit -n1000 -r10000
factorial(1000)
163 µs ± 13.2 µs per loop (mean ± std. dev. of 10000 runs, 1000 loops each)
def factorial2(n):
r = 0
for i in range(n+1):
r += i
return r
%%timeit -n1000 -r10000
factorial2(1000)
The slowest run took 9.46 times longer than the fastest. This could mean that an intermediate result is being cached. 58.7 µs ± 25.2 µs per loop (mean ± std. dev. of 10000 runs, 1000 loops each)
Thanks and happy coding!