[Python-Dev] Usage of += on strings in loops in stdlib

Serhiy Storchaka storchaka at gmail.com
Wed Feb 13 15:40:47 CET 2013


On 13.02.13 15:23, Lennart Regebro wrote:
> On Wed, Feb 13, 2013 at 1:10 PM, Serhiy Storchaka <storchaka at gmail.com> wrote:
>> I prefer "x = '%s%s%s%s' % (a, b, c, d)" when string's number is more than 3
>> and some of them are literal strings.
> 
> This has the benefit of being slow both on CPython and PyPy. Although
> using .format() is even slower. :-)

Only slightly.

$ ./python -m timeit -s "spam = 'spam'; ham = 'ham'"  "spam + ' = ' + ham + '\n'"
1000000 loops, best of 3: 0.501 usec per loop
$ ./python -m timeit -s "spam = 'spam'; ham = 'ham'"  "''.join([spam, ' = ', ham, '\n'])"
1000000 loops, best of 3: 0.504 usec per loop
$ ./python -m timeit -s "spam = 'spam'; ham = 'ham'"  "'%s = %s\n' % (spam, ham)"
1000000 loops, best of 3: 0.524 usec per loop

But the last variant looks better for me.




More information about the Python-Dev mailing list