Quickest way to build a long string?

Greg Landrum glandrum at my-deja.com
Thu Oct 12 18:20:21 EDT 2000


In article <eelbuss11os1qi2hu5e6iidlql2olctb2j at 4ax.com>,
  dale at out-think.NOSPAM.co.uk wrote:
> That's excellent. Thanks very much. :^)

You're welcome.

>
> You wouldn't like to post your code would you? I'm curious to know how
> closely your approach is likely to match my own.

Sure, look below.

> Also - what method did you use to profile?

I used the python profiler.  Check the bottom of the code.

-greg

#--------------
import string

block = 'a'*100

def AddBuild(nToAdd):
    res = ''
    for i in xrange(nToAdd):
        res = res + block

def JoinBuild(nToAdd):
    res = []
    for i in xrange(nToAdd):
        res.append(block)

    string.join(res,'')

def JoinBuild2(nToAdd):
    res = ['']*nToAdd
    for i in xrange(nToAdd):
        res[i] = block

    string.join(res,'')

import profile
import pstats

nToDo = 5000
print 'running add'
profile.run('AddBuild(nToDo)','add.dat')
print 'running join'
profile.run('JoinBuild(nToDo)','join.dat')
print 'running join2'
profile.run('JoinBuild2(nToDo)','join2.dat')

for fName in ['add.dat','join.dat','join2.dat']:
    print 'data from: %s'%fName
    stats = pstats.Stats(fName)
    stats.sort_stats('time').print_stats(5)



Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list