Python’s pound of flesh
When I was a bit younger (in the late 90s), I always was very optimistic for the optimisations, that the compilers and the runtime environments could offer. For example, I always thought that the Java Virtual Machine does String pooling (it does in a way), or that databases can have fast and transparent ways to index data and quickly search them. The truth is that they do in a way, but up to a point.
Python
… is famous for its speed, or at least, not for its speed. Python is an easy programming language that allows you to do many-many things, but not executing them fast.
One day, I saw a video on youtube, which present a quick optimisation trick. The case is simple, when you reference a global variable in a method, inside a Python module and perform a loop for example, then for each iteration, the interpreter tries to reference it and get the value resulting to a performance penalty.
I was a bit shocked, when I saw it and I tried to write a small program and test it myself.
Case 1: The global-local reference problem
Consider the following program:
STEP = 2
def global_ref():
res = 0
for i in range(1000):
res += STEP