# Re: Bitwise OR?

Discussion in 'Python' started by Jean-Paul Calderone, Mar 24, 2006.

1. ### Jean-Paul CalderoneGuest

On Fri, 24 Mar 2006 15:40:17 +0100, "Diez B. Roggisch" <> wrote:
>Tim N. van der Leeuw wrote:
>> I also wonder if it wouldn't be faster to put the numbers into a list
>> and join the list into a string -- did you test with that?

>
>It will be faster - the naive string concatenation is quadratic, whereas the
>list-based approach is linear.

It won't be any faster in CPython 2.4 or newer. This kind of string concatenation is optimized so as to be linear:

\$ python -m timeit -s "x = ''" "for i in xrange(1000): x += 'x'"
1000 loops, best of 3: 335 usec per loop
\$ python -m timeit -s "x = ''" "for i in xrange(10000): x += 'x'"
100 loops, best of 3: 3.35 msec per loop
\$ python -m timeit -s "x = ''" "for i in xrange(100000): x += 'x'"
10 loops, best of 3: 33.2 msec per loop
\$ python -m timeit -s "x = ''" "for i in xrange(1000000): x += 'x'"
10 loops, best of 3: 347 msec per loop
\$ python -m timeit -s "x = ''" "for i in xrange(10000000): x += 'x'"
10 loops, best of 3: 3.48 sec per loop
\$

Jean-Paul

Jean-Paul Calderone, Mar 24, 2006

2. ### Diez B. RoggischGuest

> It won't be any faster in CPython 2.4 or newer. This kind of string
> concatenation is optimized so as to be linear:
>
> \$ python -m timeit -s "x = ''" "for i in xrange(1000): x += 'x'"
> 1000 loops, best of 3: 335 usec per loop
> \$ python -m timeit -s "x = ''" "for i in xrange(10000): x += 'x'"
> 100 loops, best of 3: 3.35 msec per loop
> \$ python -m timeit -s "x = ''" "for i in xrange(100000): x += 'x'"
> 10 loops, best of 3: 33.2 msec per loop
> \$ python -m timeit -s "x = ''" "for i in xrange(1000000): x += 'x'"
> 10 loops, best of 3: 347 msec per loop
> \$ python -m timeit -s "x = ''" "for i in xrange(10000000): x += 'x'"
> 10 loops, best of 3: 3.48 sec per loop

Interesting. I wasn't aware of that optimization.

diez

Diez B. Roggisch, Mar 24, 2006

3. ### Jorge GodoyGuest

"Diez B. Roggisch" <> writes:

> Interesting. I wasn't aware of that optimization.

It's better not count on it. It's not there for Jython, IronPython, previous
versions of Python, etc. It is just there for the new cPython. And the fix
is so simple that it isn't worth disregarding all those other versions.

--
Jorge Godoy <>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.

Jorge Godoy, Mar 24, 2006