I tried a little test:
import timeit
a = "hi"
def f():
return "hi"
def g():
return a
timeit.timeit("f()", globals={"f": f}, number=100000000)
# 6.028764325194061
timeit.timeit("g()", globals={"g": g, "a": a}, number=100000000)
# 6.053381357342005
It seems there is no difference between the normal and "cached" version... why? Maybe Python caches immutables defined in modules, functions and classes by default?
EDIT: furthermore there's a strange fact: the code
timeit.timeit("g()", globals={"g": g}, number=100000000)
gives me no error. But I have not passed the variable a
to timeit
, should not give me an exception?