5

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The compile-time optimizations can be explored a little by disassembling examples with the dis module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.