While doing Project Euler Problem 25, I came across various techniques to compute the nth Fibonacci number. Memoization seemed to be the fastest amongst them all, and intuitively, I expected memoization to be faster than creating a list from bottom-up.
The code for the two functions is:
def fib3(n): #FASTEST YET
fibs= [0,1] #list from bottom up
for i in range(2, n+1):
fibs.append(fibs[-1]+fibs[-2])
return fibs[n]
def fib4(n, computed= {0:0, 1:1}): #memoization
if n not in computed:
computed[n]= fib4(n-1, computed)+ fib4(n-2, computed)
return computed[n]
print fib3(1000)
print fib4(1000)
fib3 was approximately 8 times faster than fib4. I am unable to figure out the reason behind this. Essentially both are storing the values as they compute, one in a list, the other in a dictionary so that they can access them as "cached" later. Why the huge difference?