I'm not sure whether it's the same in Python.
Has anyone tried that before?
http://docs.python.org/library/operator#operator.iadd
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With