Yes. For the examples you chose, the importance is unclear because you only have two very short lines, so the application is likely to be faster.
But every time you do a + b with strings in Python, it calls a new selection and then copies all the bytes from a and b to a new line. If you do this in a loop with a lot of lines, these bytes must be copied again and again, and again, and each time the amount to be copied increases. This gives a quadratic behavior.
On the other hand, creating a list of strings does not copy the contents of the strings β it simply copies the links. It is incredibly fast and runs in linear time. Then the join method makes only one memory allocation and copies each line to the correct position only once. It also takes only linear time.
So yes, use idiom ''.join if you are potentially dealing with a lot of strings. For two lines this does not matter.
If you need to convince more, try creating a string of 10M characters yourself:
>>> chars = ['a'] * 10000000 >>> r = '' >>> for c in chars: r += c >>> print len(r)
Compared with:
>>> chars = ['a'] * 10000000 >>> r = ''.join(chars) >>> print len(r)
The first method takes about 10 seconds. The second takes less than 1 second.
source share