2

I just read this SE question about parameter optimisation. I wondered if Python3 bytecode compilation does the same optimisation and this appeared not to be the case:

>>> def f(a): return 2*a
>>> def g(a): r=2*a; return r
>>> import dis
>>> dis.dis(f)
  1           0 LOAD_CONST               1 (2)
              2 LOAD_FAST                0 (a)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE
>>> dis.dis(g)
  1           0 LOAD_CONST               1 (2)
              2 LOAD_FAST                0 (a)
              4 BINARY_MULTIPLY
              6 STORE_FAST               1 (r)
              8 LOAD_FAST                1 (r)
             10 RETURN_VALUE

Checking the compilation flags showed that optimization is on:

>>> print(dis.code_info(f))
Name:              f
Filename:          <stdin>
Argument count:    1
Kw-only arguments: 0
Number of locals:  1
Stack size:        2
Flags:             OPTIMIZED, NEWLOCALS, NOFREE
Constants:
   0: None
   1: 2
Variable names:
   0: a

So my question is: why doesn't Python3 optimise out the variable?

Ps: I'm not sure if this questions fits better on SE or on SO. I picked SE because the question that triggered my questions was on SE. If you think this question better fits SO, please let me know...

4

CPython is the reference implementation of the Python language. It prioritizes simplicity over performance, and does not perform any meaningful optimizations during bytecode compilation.

Also, serious performance work is expensive (as in, requires many person-years). For the problems to which Python is often applied, the current CPython performance level is often good-enough, so there has been little sponsorship for work on advanced optimizations (like using a JIT compiler). While there was project Unladen Swallow during 2009–2011, that work fizzled out. In contrast, significant time/money has been spent on JavaScript implementations because there the typical performance level of an interpreter was not good enough.

Where Python performance is critical, you generally have the following choices:

  • use ordinary optimization techniques
  • use a different Python implementation such as PyPy (which can perform way more optimizations that CPython)
  • rewrite the code as Cython and compile it.
  • rewrite the code in another language (e.g. C++) and compile it as a CPython module.

For example, many performance-critical parts in the SciPy stack are actually written in C, Fortran, or Cython.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.