[issue41242] When concating strings, I think it is better to use += than join the list
Rémi Lapeyre
report at bugs.python.org
Wed Jul 8 11:04:38 EDT 2020
Rémi Lapeyre <remi.lapeyre at henki.fr> added the comment:
Hi Wansoo, using += instead of str.join() is less performant. Concatenating n strings with + will create and allocate n new strings will str.join() will carefully look ahead and allocate the correct amount of memory and do all concatenation at one:
➜ ~ python3 -m timeit -s 's = ""' 'for i in range(1_000_000): s += "foo\n"'
5 loops, best of 5: 107 msec per loop
➜ ~ python3 -m timeit -s 'l = ["foo"]*1_000_000' '"\n".join(l)'
20 loops, best of 5: 9.96 msec per loop
It's a common idiom that you will meet a lot in Python.
----------
nosy: +remi.lapeyre
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41242>
_______________________________________
More information about the Python-bugs-list
mailing list