Accessing global variables is a known code smell, but it’s still very popular in scripts and competitive programming. For me, ability to reason about invariants, especially when concurrency is involved, is sufficient to avoid this anti-pattern, but one may easily argue that it’s a matter of personal preference and a subjective judgement.
But what if there was an objective reason to prefer one over the other? How about runtime? To make things concrete, we’ll use a super inefficient way of sorting array of random integers. One using a local list of random integers
and one using a global list
It’s time to use %timeit to see how these compare
That’s almost 1.6X speedup just by switching to a more readable and reusable code.
You can play with full code using colab. You can also see a difference in bytecode using compiler explorer, which unsurprisingly is using fast loads for local variables
and global loads for accessing global variables
As such there are no more excuses for accessing global variables.
hell yeah! :)