So this page about memoization got me curious. I ran my own benchmarks.
%%timeit
def fibo(n, dic={}) :
if n not in dic :
if n in (0,1) :
dic[n] = 1
else :
dic[n] = fibo(n-1)+fibo(n-2)
return dic[ n ]
fibo(30)
Out:
100000 loops, best of 3: 18.3 µs per loop
In [21]:
%%timeit
def fibo(n, dic={}) :
try :
return dic[n]
except :
if n in (0,1) :
dic[n] = 1
else :
dic[n] = fibo(n-1)+fibo(n-2)
return dic[ n ]
fibo(30)
Out:
10000 loops, best of 3: 46.8 µs per loop
As @kevin suggest in the comments, I got the decorator completely wrong so I removed it. The remainder is still valid! (I hope)
Catching exception means stack tracing which can be very expensive:
https://docs.python.org/2/faq/design.html#how-fast-are-exceptions
Exceptions are very efficient in two cases:
try ... finally
try ... except
, providing that no exception is thrown
However, when exception occured and caught the required stack tracing adds great overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With