Say I have a string in x
, is the Python interpreter smart enough to know that: string.replace(x, x)
should be converted to a NOP
?
How can I find this out? Are there any references that show what type of optimizations the interpreter is able to do dynamically based on syntactic analysis?
No, Python cannot make assumptions about NOPs; it cannot know at compile time what type of object string
is, nor that it'll remain that type throughout the run of the program.
There are some optimisations applied at compile time, mostly in the peephole optimiser. This does things like:
Replace list
and set
literals used in a membership test with immutable equivalents; this only works if the literal object is not assigned, only used in a comparison; e.g.:
if foo in ['spam', 'ham', 'eggs']:
is replaced with
if foo in ('spam', 'ham', 'eggs'):
Replace simple calculations with the result:
one_week = 7 * 24 * 60 * 60
is replaced with
one_week = 604800
This happens for sequences too; 'neener' * 3
is replaced with the result of that multiplication, provided the resulting sequence stays under 21 elements.
These optimisations are only possible because it concerns immutable literal values; constant values that are fully under control of the interpreter and can be relied upon to not switch types halfway through execution.
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