My understanding is that appending to a list and then joining this list when done is the fastest technique for string concatenation. Is this true?
The 3 string concatenation techniques I can think of are: - append to list, join - string 'addition' (s = s + char) - cStringIO The code that follows my signature confirms that the list append/join technique is indeed the fastest of these 3 approaches, but perhaps there are other techniques I should consider? Malcolm # test various techniques for string concatenation import cStringIO import timeit source = 'x' * 5000000 def testListAppend(): output = list() for char in source: output.append( char ) output = ''.join( output ) def testStringConcat(): output = '' for char in source: output += char def testStringIO(): output = cStringIO.StringIO() for char in source: output.write( char ) output = output.getvalue() def time( func ): timingObject = timeit.Timer( func ) runtime = timingObject.timeit( 10 ) print '%s = %.2f sec' % ( func.__name__, runtime ) time( testListAppend ) time( testStringConcat ) time( testStringIO ) Output using Python 2.7 (32-bit) under Windows 7 (64-bit) testListAppend = 10.38 sec testStringConcat = 53.01 sec testStringIO = 13.85 sec
-- http://mail.python.org/mailman/listinfo/python-list