relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

Hans Mulder hansmu at xs4all.nl
Sun Aug 21 13:57:50 EDT 2011


On 21/08/11 19:14:19, Irmen de Jong wrote:

> What the precise difference (semantics and speed) is between the
> BINARY_ADD and INPLACE_ADD opcodes, I dunno. Look in the Python source
> code or maybe someone knows it from memory :-)

There is a clear difference in semantics: BINARY_ADD always produces
a new object, INPLACE_ADD may modify its left-hand operand in situ
(if it's mutable).

Integers are immutable, so for integers the semantics are the same,
but for lists, for example, the two are different:

 >>> x = [2, 3, 5, 7]
 >>> y = [11, 13]
 >>> x+y
[2, 3, 5, 7, 11, 13]
 >>> x
[2, 3, 5, 7]		# x still has its original value
 >>> x += y
 >>> x
[2, 3, 5, 7, 11, 13]	# x is now modified
 >>>

For integers, I would not expect a measurable difference in speed.

Hope this helps,

-- HansM




More information about the Python-list mailing list