As a result of the comments in my answer on this thread, I wanted to know what the speed difference is between the +=
operator and ''.join()
So what is the speed comparison between the two?
As a result of the comments in my answer on this thread, I wanted to know what the speed difference is between the +=
operator and ''.join()
So what is the speed comparison between the two?
This is what silly programs are designed to test :)
Use plus
Output of:
Now with join....
Output Of:
So on python 2.6 on windows, I would say + is about 18 times faster than join :)
I rewrote the last answer, could jou please share your opinion on the way i tested?
NOTE: This example is written in Python 3.5, where range() acts like the former xrange()
The output i got:
Personally i prefer ''.join([]) over the 'Plusser way' because it's cleaner and more readable.
From: Efficient String Concatenation
Method 1:
Method 4:
Now I realise they are not strictly representative, and the 4th method appends to a list before iterating through and joining each item, but it's a fair indication.
String join is significantly faster then concatenation.
Why? Strings are immutable and can't be changed in place. To alter one, a new representation needs to be created (a concatenation of the two).
My original code was wrong, it appears that
+
concatenation is usually faster (especially with newer versions of Python on newer hardware)The times are as follows:
Python 3.3 on Windows 7, Core i7
Python 2.7 on Windows 7, Core i7
On Linux Mint, Python 2.7, some slower processor
And here is the code:
The existing answers are very well-written and researched, but here's another answer for the Python 3.6 era, since now we have literal string interpolation (AKA,
f
-strings):Test performed using CPython 3.6.5 on a 2012 Retina MacBook Pro with an Intel Core i7 at 2.3 GHz.
This is by no means any formal benchmark, but it looks like using
f
-strings is roughly as performant as using+=
concatenation; any improved metrics or suggestions are, of course, welcome.