<!--/*SC*/DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"/*EC*/-->
<html><head><title></title><style type="text/css"><!--body{padding:1ex;margin:0px;font-family:sans-serif;font-size:small;}a[href]{color:-moz-hyperlinktext !important;text-decoration:-moz-anchor-decoration;}blockquote{margin:0;border-left:2px solid #144fae;padding-left:1em;}blockquote blockquote{border-color:#006312;}blockquote blockquote blockquote{border-color:#540000;}--></style></head><body><div style="font-family: Arial; font-size: medium;" dir="ltr"><div>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?</div>
<div> </div>
<div>The 3 string concatenation techniques I can think of are:</div>
<div> </div>
<div>- append to list, join</div>
<div>- string 'addition' (s = s + char)</div>
<div>- cStringIO</div>
<div> </div>
<div>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?</div>
<div> </div>
<div>Malcolm</div>
<div> </div>
<div># test various techniques for string concatenation</div>
<div><br>
import cStringIO<br>
import timeit<br>
<br>
source = 'x' * 5000000<br>
<br>
def testListAppend():<br>
    output = list()<br>
    for char in source:<br>
        output.append( char )<br>
    output = ''.join( output )<br>
    <br>
def testStringConcat():<br>
    output = ''<br>
    for char in source:<br>
        output += char<br>
    <br>
def testStringIO():    <br>
    output = cStringIO.StringIO()<br>
    for char in source:<br>
        output.write( char )<br>
    output = output.getvalue()<br>
    <br>
def time( func ):<br>
    timingObject = timeit.Timer( func )<br>
    runtime = timingObject.timeit( 10 )<br>
    print '%s = %.2f sec' % ( func.__name__, runtime )<br>
<br>
time( testListAppend )<br>
time( testStringConcat )<br>
time( testStringIO )<br>
 </div>
<div>Output using Python 2.7 (32-bit) under Windows 7 (64-bit)</div>
<div> </div>
<div>testListAppend = 10.38 sec<br>
testStringConcat = 53.01 sec<br>
testStringIO = 13.85 sec</div>
<div> </div></div></body></html>