pythonoptimization

Is there any performance difference between calling a local variable and calling an object's instance variable?


Here's the code I have:

        elif line.mesg.startswith('^^'):
            recog, score = pull_recog(line)
            line.recog = recog
            line.score = score

            print recog + ' '*(20-len(recog)) + '%2.2f'%score

This question really comes down to how the compiler takes care of this:

Does the compiler optimize this code in some way that would make no difference between:

  1. Calling the local variables recog and score
  2. Calling the object's instance variables line.score and line.recog?

My initial instinct that using the local variables would be quicker, but I'm not getting good results from timeit so I can't really tell for sure.

This is within a for-loop, so optimization does actually matter in this case.


Solution

  • Local variables are quicker. line.score is two operations: a local variable retrieval (for line) and an attribute lookup (for score). Whereas recog is only one operation, the local variable retrieval. One operation is faster than two, especially when one of the two is the same as the one.

    You can see this very easily by inspecting the bytecode using the dis module.

    from dis import dis
    
    def myfunc(recog, line):
        recog
        line.score
    
    dis(myfunc)
    

    This part is the reference to recog:

     2           0 LOAD_FAST                0 (recog)
    

    And this is line.score:

     3           4 LOAD_FAST                1 (line)
                 7 LOAD_ATTR                0 (score)
    

    Q.E.D.