I am still new to Python, and I have been trying to improve the performance of my Python script, so I tested it with and without global variables. I timed it, and to my surp
Simple Answer:
Due to Python's dynamic nature, when the interpreter comes across an expression like a.b.c, it looks up a (trying first the local namespace, then the global namespace, and finally the built-in namespace), then it looks in that object's namespace to resolve the name b, and finally it looks in that object's namespace to resolve the name c. These lookups are reasonably fast; For local variables, lookups are extremely fast, since the interpreter knows which variables are local and can assign them a known position in memory.
Interpreter knows which names inside your functions are local and it assigns them specific (known) locations inside the function call's memory. This makes references to locals much faster than to globals and (most especially) to built-ins.
Code example to explain the same:
>>> glen = len # provides a global reference to a built-in
>>>
>>> def flocal():
... name = len
... for i in range(25):
... x = name
...
>>> def fglobal():
... for i in range(25):
... x = glen
...
>>> def fbuiltin():
... for i in range(25):
... x = len
...
>>> timeit("flocal()", "from __main__ import flocal")
1.743438959121704
>>> timeit("fglobal()", "from __main__ import fglobal")
2.192162036895752
>>> timeit("fbuiltin()", "from __main__ import fbuiltin")
2.259413003921509
>>>