Steve D'Aprano, you're the "master". What's wrong with this concatenation statement?

Chris Angelico rosuav at gmail.com
Thu May 12 04:40:22 EDT 2016


On Thu, May 12, 2016 at 6:23 PM, srinivas devaki
<mr.eightnoteight at gmail.com> wrote:
> On May 9, 2016 5:31 AM, "Tim Chase" <python.list at tim.thechases.com> wrote:
>>
>> then that's a bad code-smell (you get quadratic behavior as the
>> strings are constantly resized), usually better replaced with
>>
>
> I just want to point out that in Python s += str in loop is not giving
> quadratic behavior. I don't know why but it runs fast. I'm very much
> interested to know why it is so?
>
> In [3]: %%timeit
>    ...: s = ''
>    ...: for x in xrange(10**6):
>    ...:     s += str(x)
>    ...:
> 1 loop, best of 3: 383 ms per loop
>
> In [4]: %%timeit
> s = ''
> for x in xrange(10**6):
>     s = s + str(x)
>    ...:
> 1 loop, best of 3: 383 ms per loop

Some versions of CPython do include an optimization for this. However,
it's not guaranteed, and it's easy to disrupt. For starters, it works
only if you're appending to a string, not prepending; this will be
much slower:

s = ''
for x in range(10**6):
    s = str(x) + s

And other Pythons may not optimize this. So don't depend on it.

ChrisA



More information about the Python-list mailing list