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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With