This wiki is in the process of being archived due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies. Edits are discouraged.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

Counter to the PythonSpeed/PerformanceTips, on python 2.4 the following string concatenation is almost twice as fast:

   1 from time import time
   2 t = time()
   3 
   4 s = 'lksdajflakjdsflku09uweoir'
   5 for x in range(40):
   6     s += s[len(s)/2:]
   7 
   8 print 'duration:', time()-t

as:

   1 from time import time
   2 t = time()
   3 
   4 s = 'lksdajflakjdsflku09uweoir'
   5 for x in range(40):
   6     s = "".join((s, s[len(s)/2:]))
   7 
   8 print 'duration:', time()-t


On the win32 Python 2.4 I'm seeing the join sample above complete in less than half the time of the concatenating sample.

Usually the join() is located outside the loop, that code makes this extremely hard though (becuase of the self-referencing of the generated string). But that situation is not the norm. -- JürgenHermann 2005-08-01 06:07:51

Are you guys kidding? The whole page is contrieved. Correct implementation of "join" is:

from time import time
t = time()

s = 'lksdajflakjdsflku09uweoir'
r = [s]
for x in range(40):
    r.append(s[len(s)/2:])
s = "".join(r)

print 'duration:', time()-t

which gives on PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32 execution times:

1st  duration: 54.4060001373
Last duration: 0.0160000324249

-- -- MikeRovner 2005-08-02 10:19:06

-- -- DavidFord 2005-10-18 10:19:06 A few notes (your mileage may vary - this is a 4Mb file being stripped of unprintable characters)


I tend to create a stream of strings in a loop that should be concatenated. I generated the script to test the join vs += performance for some randomly generated data and found that for 100,000 strings of length up to ten characters, join is maybe 20% faster than using +=. It certainly was not an order of magnitude faster. The results tended to vary each time through the outer loop, even though I attempted to control the garbage collection and ensured my Windows XP machine was 95% idle apart from running the script.

   1 from time import time
   2 import random, gc
   3 
   4 '''
   5 Check speed of string concatenation vs joining in different versions of Python
   6 
   7 
   8 
   9 Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32