When you run timeit.timeit
without specifying an argument to the keyword number
, it executes the code that you pass it 1000000 times. If you keep a global dictionary called fac_mem
in the global scope for Python, it will save the results of the first execution in that dictionary.
Therefore your memoized factorial function will only be slow on the first execution where it actually has to do the computations. The rest of the 999999 times it will simply look up the answers in the dictionary and avoid doing computations.
If you keep the dictionary inside the function, it will be destroyed after every time Python leaves the scope within the function (since all references to the dictionary will be destroyed when the function returns). Thus the dictionary will not be able to save its answers and will still remain slow for future executions.