The string join method can concatenate strings significantly faster than using the '+' operator. I think Raymond Hettinger talked about this in one of his presentations archived on pyvideo.org.


In [1]:
width = 1000

In [2]:
def foo(width):
    horizontal_line = '{'
    for i in range(width):
        horizontal_line += (' ' + '#ffffff')
    horizontal_line += '}'

In [3]:
%timeit foo(width)


1000 loops, best of 3: 210 µs per loop

In [4]:
def foo(width):
    horizontal_line = (
        '{' +
        ' '.join(
            '#ffffff' for i in range(width)
        ) +
        '}'
    )

In [5]:
%timeit foo(width)


10000 loops, best of 3: 129 µs per loop

In [6]:
def foo(width):
    horizontal_line = ''.join([
        '{',
        ' '.join(
            '#ffffff' for i in range(width)
        ),
        '}',
    ])

In [7]:
%timeit foo(width)


10000 loops, best of 3: 129 µs per loop