fastest string building?

Neil Schemenauer nascheme at enme.ucalgary.ca
Tue Oct 19 16:01:28 EDT 1999


Preston Landers <prestonlanders at my-deja.com> wrote:
>Can someone look at my profiling script and see if I made any obvious
>errors?  Is behavior of strings already well-known?

I think you under-estimated the difficulty of benchmarking. :)

The speed of each method depends on the situation.  Method 1 is
really bad if you continuously add characters on the end of a
long string:

    spam = ''
    for i in range(10000):
        spam = spam + 'a'

This creates and destroys a string object each time around the
loop.  In this case, method 2 or [c]StringIO is much better:

    spam = []
    for i in range(10000):
        spam.append('a')
    spam = string.join(spam, '')

I believe this is the primary use of the string.join idiom.  I
would never write:

    spam = string.join([a, b, c])

but rather:

    spam = '%s%s%s%s' % (a, b, c)

or even:

    spam = a + b + c

if I am lazy and the strings are not expected to be huge.


    Neil




More information about the Python-list mailing list