On Sun, 21 Aug 2011 09:52:23 -0700, Laurent wrote:

> I did many tests and "i = i + 1" always seems to be around 2% faster
> than "i += 1". This is no surprise as the += notation seems to be a
> syntaxic sugar layer that has to be converted to i = i + 1 anyway. Am I
> wrong in my interpretation? 

It depends. If the value on the left has an __iadd__ method, that will be
called; the value will be updated in-place, so all references to that
object will be affected:

        > import numpy as np
        > a = np.zeros(3)
        > b = a
        > a
        array([ 0.,  0.,  0.])
        > b
        array([ 0.,  0.,  0.])
        > a += 1
        > a
        array([ 1.,  1.,  1.])
        > b
        array([ 1.,  1.,  1.])

If the value on the left doesn't have an __iadd__ method, then addition is
performed and the name is re-bound to the result:

        > a = a + 1
        > a
        array([ 2.,  2.,  2.])
        > b
        array([ 1.,  1.,  1.])

If you're writing code which could reasonably be expected to work with
arbitrary "numeric" values, you should decide which to use according to
whether in-place modification is appropriate rather than trivial
performance differences. If a difference of a few percent is significant,
Python is probably the wrong language in the first place.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to