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)
In [4]:
def foo(width):
horizontal_line = (
'{' +
' '.join(
'#ffffff' for i in range(width)
) +
'}'
)
In [5]:
%timeit foo(width)
In [6]:
def foo(width):
horizontal_line = ''.join([
'{',
' '.join(
'#ffffff' for i in range(width)
),
'}',
])
In [7]:
%timeit foo(width)