Efficient String Concatenation in Python
skymind.com
Efficient String Concatenation in Python
1–10 of 29 posts
Re: Efficient String Concatenation in Python
#2 return ''.join(`num` for num in xrange(loop_count))
On one hand, it avoids creating a temporary list in memory. On the other, it can't know in advance how long the final output of the loop will be and so couldn't use tricks like preallocating enough RAM.Re: Efficient String Concatenation in Python
#3Re: Efficient String Concatenation in Python
#4Re: Efficient String Concatenation in Python
#5How would a method 7 using generator expressions fare on the same system, like: return ''.join(`num` for num in xrange(loop_count)) On one hand, it avoids creating a temporary list in memory. On the other, it can't know in advance how long the final output of the loop will be and so couldn't use tricks like preallocating enough RAM.
http://docs.python.org/2/library/timeit.html
Results:
$ python -m timeit '"-".join(str(n) for n in range(100))'
10000 loops, best of 3: 40.3 usec per loop
$ python -m timeit '"-".join([str(n) for n in range(100)])'
10000 loops, best of 3: 33.4 usec per loop
$ python -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 3: 25.2 usec per loopRe: Efficient String Concatenation in Python
#6 ''.join(map(str, range(n)))Re: Efficient String Concatenation in Python
#7How would a method 7 using generator expressions fare on the same system, like: return ''.join(`num` for num in xrange(loop_count)) On one hand, it avoids creating a temporary list in memory. On the other, it can't know in advance how long the final output of the loop will be and so couldn't use tricks like preallocating enough RAM.
Re: Efficient String Concatenation in Python
#8 s1 += s2
There are details at point six of http://docs.python.org/2/library/stdtypes.html#sequence-type..., where it also says that str.join() is preferable.Re: Efficient String Concatenation in Python
#9Note that since this article was written (2004) CPython performs an in-place optimisation for assignments of the form s1 += s2 There are details at point six of http://docs.python.org/2/library/stdtypes.html#sequence-type... , where it also says that str.join() is preferable.
Re: Efficient String Concatenation in Python
#10Note that since this article was written (2004) CPython performs an in-place optimisation for assignments of the form s1 += s2 There are details at point six of http://docs.python.org/2/library/stdtypes.html#sequence-type... , where it also says that str.join() is preferable.
Does PyPy have the same heuristic? If not, I wouldn't recommend relying on it.