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 surprise, it ran faster with global variables declared rather than passing local vars to functions. What’s going on? I thought execution speed was faster with local variables? (I know globals are not safe, I am still curious.)
Share
Locals should be faster
According to this page on locals and globals:
Based on that, I’d assume that local variables are generally faster. My guess is what you’re seeing is something particular about your script.
Locals are faster
Here’s a trivial example using a local variable, which takes about 0.5 seconds on my machine (0.3 in Python 3):
And the global version, which takes about 0.7 (0.5 in Python 3):
globaldoes something weird to variables that are already globalInterestingly, this version runs in 0.8 seconds:
While this runs in 0.9:
You’ll notice that in both cases,
xis a global variable (since there’s no functions), and they’re both slower than using locals. I have no clue why declaringglobal xhelped in this case.This weirdness doesn’t occur in Python 3 (both versions take about 0.6 seconds).
Better optimization methods
If you want to optimize your program, the best thing you can do is profile it. This will tell you what’s taking the most time, so you can focus on that. Your process should be something like: