Confounded by Python objects

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jul 27 18:13:46 EDT 2008


On Sun, 27 Jul 2008 20:04:27 +0200, Bruno Desthuilliers wrote:

>> In general, anything that looks like this:
>> 
>> s = ''
>> for i in range(10000):  # or any big number
>>     s = s + 'another string'
>> 
>> can be slow. Very slow.
> 
> But this is way faster:
> 
> s = ''
> for i in range(10000):  # or any big number
>      s += 'another string'

Actually, no, for two reasons:

(1) The optimizer works with both s = s+t and s += t, so your version is 
no faster than mine.

(2) The optimization isn't part of the language. It only happens if you 
are using CPython versions better than 2.4, and even then not guaranteed.

People forget that CPython isn't the language, it's just one 
implementation of the language, like Jython and IronPython. Relying on 
the optimization is relying on an implementation-specific trick.

> yeps : using augmented assignment (s =+ some_string) instead of
> concatenation and rebinding (s = s + some_string).

Both are equally optimized.

>>> timeit.Timer('s+=t', 's,t="xy"').repeat(number=100000)
[0.027187108993530273, 0.026471138000488281, 0.027689933776855469]
>>> timeit.Timer('s=s+t', 's,t="xy"').repeat(number=100000)
[0.026300907135009766, 0.02638697624206543, 0.02637791633605957]

But here's a version without it:

>>> timeit.Timer('s=t+s', 's,t="xy"').repeat(number=100000)
[2.1038830280303955, 2.1027638912200928, 2.1031770706176758]



-- 
Steven



More information about the Python-list mailing list