Suppose I have the following in a really tight loop:
a = func(x)
b = func2(a)
The variable a is not used anywhere else.
Does Python automatically compile away the assignment to a, or does it take the time to do the variable assignment every time? In other words, is this code identical, or is it marginally faster due to the lack of assigning to a?
b = func2(func(x))
Is the behavior the same for Python2.7 vs Python3?
So using the very fun
dismodule we can look into the actual bytecode that is generated from the python code you provided. To keep things simple I have replacedfuncandfunc2with builtin functions (intandfloat).So our source looks like this:
Versus a simplified version:
And then starting with the cpython 2.7 interpretter, we can see the bytecodes generated from the
assignfunction:As you can see there is no peephole optimization to remove the unnecessary intermediate variable, which results in an additional 2 instructions (
STORE_FAST a,LOAD_FAST a) when compared against the bytecodes for the simplified `simple method:This is the same for the CPython interpreter for Python 3.5, and for the pypy interpreter for Python 2.7.