relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Aug 22 00:14:32 EDT 2011
On Mon, 22 Aug 2011 12:08 pm Stephen Hansen wrote:
> Picking "i += 1" over "i = i + 1" based on one being 4% slower is sorta
> kinda crazy. The difference in speed is probably related to churn and
> cache as much as anything else (its not as consistent on my machine, for
> example): or the ceval loop doing a few more case-tests between them as
> others have mentioned. All in all, if 4% of a nanomicrofraction of a
> chunk of time is that meaningful, you're probably best served not using
> Python. :)
Agreed.
But...
> That said: my advice is always to avoid += like a plague. It is magic
> and impossible to predict without intimate knowledge of exactly what's
> on the left-side.
>
> i += 1
> n += x
>
> Those two things look very similar, but they may do -completely-
> different things depending on just what "n" is.
Technically, the *exact same criticism* can be applied to:
n = n + x
since either n or x could override __add__ or __radd__ and do anything it
bloody well likes. Including in-place modification of *either* argument
(where possible).
[...]
> With "i = i + 1", I know that generally speaking, my "i" is being
> assigned a new object and that's that, no matter what type "i" is.
> (Okay: I do know that you could modify __add__ to do something
> underhanded here, tweaking internal state and then returning self.
What makes you think that's underhanded?
To my mind, __add__ modifying self as a side-effect is unusual, but apart
from breaking the general rule of thumb to avoid side-effects, not
particularly evil. (But I would accept this is a code smell.)
> People going out of their way to behave unpredictably is not my
> objection: supposedly easy and straight-forward normal Python-fu being
> inherently unpredictable is).
>
> For example: I just /know/ that it doesn't matter who or what may have
> their own binding to that object before I go and increment it, they
> won't be affected and everything just will work fine.
But you can't /know/ that at all, unless you know that the object
isn't "underhanded" (however you define that!). And given some arbitrary
object, how can you know that?
--
Steven
More information about the Python-list
mailing list