String concatenation performance with +=

Steven D'Aprano steve at pearwood.info
Sat Feb 14 22:44:45 EST 2009


Nick Craig-Wood wrote:

> The optimized += depends on their being no other references to the
> string.  Strings are immutable in python.  So append must return a new
> string.  However the += operation was optimised to do an in-place
> append if and only if there are no other references to the string.
> 
> You can see this demonstrated here
> 
> $ python -m timeit -s 'a="x"' 'a+="x"'
> 1000000 loops, best of 3: 0.231 usec per loop
> 
> $ python -m timeit -s 'a="x"; b=a' 's = a; a+="x"'
> 100000 loops, best of 3: 30.1 usec per loop

That is a fantastic explanation of why you shouldn't rely on the concat
optimization, although the assignment b=a in the setup isn't necessary and
is a little misleading. Thank you.


-- 
Steven




More information about the Python-list mailing list