timakro
timakro

Reputation: 1841

Are simple hardcoded arithmetics cached/compiled away?

I would like to know if python caches / compiles away in its .pyc files simple arithmetics like 5*5+5.

Sometimes I like to write if seconds > 24*60*60 for a day for example. I know that the effect on performance is unnoticeable but I'm curious nevertheless.

Upvotes: 4

Views: 66

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123032

Yes, CPython (the default implementation of Python) uses a peephole optimiser to collapse such expressions into one number; this is called constant folding.

You can check for this using the dis disassembler:

>>> import dis
>>> def foo():
...     if seconds > 24*60*60:
...         pass
...
>>> dis.dis(foo)
  2           0 LOAD_GLOBAL              0 (seconds)
              3 LOAD_CONST               4 (86400)
              6 COMPARE_OP               4 (>)
              9 POP_JUMP_IF_FALSE       15

  3          12 JUMP_FORWARD             0 (to 15)
        >>   15 LOAD_CONST               0 (None)
             18 RETURN_VALUE

Note the LOAD_CONST instruction at offset 3; it loads the final result of the 24*60*60 expression, the expression itself is gone from the bytecode.

See the fold_binops_on_constants function in the peephole.c file.

Upvotes: 7

Related Questions