The fact the global
variables in python
are slower than local
ones is pretty well known and has already been discussed in different questions in this site. However, one thing I still haven't found an answer for is, what's the best and fastest way to use global
variables (like constant
, a concept that doesn't exist in python) that are used inside different functions in the code?
The best solution I could find so far is to define a closure
function where I assign the global variable to the local one.
from timeit import timeit
number = 10
def flocal():
number = 10
for i in range(25):
x = number
def fglobal():
for i in range(25):
x = number
def fglobal_wrapper():
global_number = number
def actual_func():
for i in range(25):
x = global_number
return actual_func
fclosure = fglobal_wrapper()
print("local: %.3f" % timeit("flocal()", "from __main__ import flocal"))
print("global: %.3f" % timeit("fglobal()", "from __main__ import fglobal"))
print("closure: %.3f" % timeit("fclosure()", "from __main__ import fclosure"))
Output:
local: 0.681
global: 0.806
closure: 0.728
But that's an ugly solution, and it's still slower then using a local variable. What is the best known method to use a global/constant variable equivalent inside functions, without having to use pass them as arguments to the function, or this closure
workaround?