Python interpreter optimization

Say I have a string in x , is the Python interpreter smart enough to know that: string.replace(x, x) should be converted to NOP ?

How can I find out? Are there any links that show what types of optimizations the interpreter can perform dynamically based on parsing?

+5
source share
1 answer

No, Python cannot make assumptions about NOP; he cannot know at compile time what type of string object is, and that he will remain that type throughout the entire program run.

There are several optimizations during compilation, mainly in the peephole optimizer . It does things like:

  • Replace list and set literals used in the membership test with immutable equivalents; this only works if the literal object is not assigned, it is used only in comparison; eg:.

     if foo in ['spam', 'ham', 'eggs']: 

    replaced by

     if foo in ('spam', 'ham', 'eggs'): 
  • Replace simple calculations with the result:

     one_week = 7 * 24 * 60 * 60 

    replaced by

     one_week = 604800 

    This also happens for sequences; 'neener' * 3 is replaced by the result of this multiplication if the resulting sequence remains within 21 elements.

These optimizations are possible only because they are associated with immutable literal values; constant values ​​that are completely under the control of the interpreter, and you can rely on them to not switch types halfway through execution.

+5
source

Source: https://habr.com/ru/post/1200047/


All Articles