Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #11964
| From | Nobody <nobody@nowhere.com> |
|---|---|
| Subject | Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") |
| Date | 2011-08-21 22:07 +0100 |
| Message-Id | <pan.2011.08.21.21.07.55.886000@nowhere.com> |
| Newsgroups | comp.lang.python |
| References | <8c606fc1-0aa8-4113-b607-e46ad6f3d649@glegroupsg2000goo.googlegroups.com> |
| Organization | Zen Internet |
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Laurent <laurent.payot@gmail.com> - 2011-08-21 09:52 -0700
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") woooee <woooee@gmail.com> - 2011-08-21 09:59 -0700
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Laurent <laurent.payot@gmail.com> - 2011-08-21 10:03 -0700
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Irmen de Jong <irmen@-NOSPAM-xs4all.nl> - 2011-08-21 19:14 +0200
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Hans Mulder <hansmu@xs4all.nl> - 2011-08-21 19:57 +0200
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Nobody <nobody@nowhere.com> - 2011-08-21 22:07 +0100
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Laurent Payot <laurent.payot@gmail.com> - 2011-08-21 16:49 -0700
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Terry Reedy <tjreedy@udel.edu> - 2011-08-21 22:15 -0400
Re: relative speed of incremention syntaxes (or "i=i+1" VS "i+=1") Terry Reedy <tjreedy@udel.edu> - 2011-08-21 20:35 -0400
csiph-web