Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a+=1 be faster than a = a+1 in Python?

I'm not sure whether it's the same in Python.

Has anyone tried that before?

http://docs.python.org/library/operator#operator.iadd

like image 599
Hanfei Sun Avatar asked Aug 23 '26 23:08

Hanfei Sun


1 Answers

There hardly is a difference in the work python performs for either statement:

>>> import dis
>>> def inplace_add():
...     a = 0
...     a += 1
... 
>>> def add_and_assign():
...     a = 0
...     a = a + 1
... 
>>> dis.dis(inplace_add)
  2           0 LOAD_CONST               1 (0)
              3 STORE_FAST               0 (a)

  3           6 LOAD_FAST                0 (a)
              9 LOAD_CONST               2 (1)
             12 INPLACE_ADD         
             13 STORE_FAST               0 (a)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE        
>>> dis.dis(add_and_assign)
  2           0 LOAD_CONST               1 (0)
              3 STORE_FAST               0 (a)

  3           6 LOAD_FAST                0 (a)
              9 LOAD_CONST               2 (1)
             12 BINARY_ADD          
             13 STORE_FAST               0 (a)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE        

The difference is a INPLACE_ADD versus a BINARY_ADD.

The resulting timings are too close to call which one would be faster:

>>> import timeit
>>> timeit.timeit('inplace_add', 'from __main__ import inplace_add', number=10000000)
0.32667088508605957
>>> timeit.timeit('add_and_assign', 'from __main__ import add_and_assign', number=10000000)
0.34172606468200684

So, in python, the difference is negligible. Don't worry about it.

like image 148
Martijn Pieters Avatar answered Aug 25 '26 14:08

Martijn Pieters