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?
Advertisement
Answer
From: Efficient String Concatenation
Method 1:
JavaScript
x
6
1
def method1():
2
out_str = ''
3
for num in xrange(loop_count):
4
out_str += 'num'
5
return out_str
6
Method 4:
JavaScript
1
6
1
def method4():
2
str_list = []
3
for num in xrange(loop_count):
4
str_list.append('num')
5
return ''.join(str_list)
6
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).