Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpreter optimization in Python

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?

like image 443
Amelio Vazquez-Reina Avatar asked Aug 11 '14 17:08

Amelio Vazquez-Reina


1 Answers

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.

like image 117
Martijn Pieters Avatar answered Oct 11 '22 16:10

Martijn Pieters