it pretty much depends on the relative sizes of the new string after every new concatenation.
With the +
operator, for every concatenation a new string is made. If the intermediary strings are relatively long, the +
becomes increasingly slower because the new intermediary string is being stored.
Consider this case:
from time import time
stri=''
a='aagsdfghfhdyjddtyjdhmfghmfgsdgsdfgsdfsdfsdfsdfsdfsdfddsksarigqeirnvgsdfsdgfsdfgfg'
l=[]
#case 1
t=time()
for i in range(1000):
stri=stri+a+repr(i)
print time()-t
#case 2
t=time()
for i in xrange(1000):
l.append(a+repr(i))
z=''.join(l)
print time()-t
#case 3
t=time()
for i in range(1000):
stri=stri+repr(i)
print time()-t
#case 4
t=time()
for i in xrange(1000):
l.append(repr(i))
z=''.join(l)
print time()-t
Results
1 0.00493192672729
2 0.000509023666382
3 0.00042200088501
4 0.000482797622681
In the case of 1&2, we add a large string, and join() performs about 10 times faster. In case 3&4, we add a small string, and '+' performs slightly faster