Saturday, July 5, 2014

Python string concatenation

Continuing with our timing and efficiency theme: What is the more efficient way of building up a string?

from cStringIO import StringIO

def string_concat(size=int(1e6)):
  repeat = 'A'
  st = ''
  for n in range(size):
    st += repeat
  return st

def list_concat(size=int(1e6)):
  repeat = 'A'
  st = []
  for n in range(size):
    st += repeat
  return ''.join(st)

def stringIO_concat(size=int(1e6)):
  repeat = 'A'
  buf = StringIO()
  for n in range(size):
    buf.write(repeat)
  return buf.getvalue()

Turns out the simple way is best:

In [91]: %timeit string_concat()
10 loops, best of 3: 121 ms per loop

In [92]: %timeit list_concat()
1 loops, best of 3: 293 ms per loop

In [93]: %timeit stringIO_concat()
1 loops, best of 3: 336 ms per loop

No comments:

Post a Comment