best way to replace first word in string?

Mike Meyer mwm at mired.org
Sun Oct 23 01:30:36 EDT 2005


Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> On Sat, 22 Oct 2005 14:54:24 -0400, Mike Meyer wrote:
>>> The string formatting is two orders of magnitude faster than the
>>> concatenation. The speed difference becomes even more obvious when you
>>> increase the number of strings being concatenated:
>> The test isn't right - the addition test case includes the time to
>> convert the number into a char, including taking a modulo.
> I wondered if anyone would pick up on that :-)
> You are correct, however that only adds a constant amount of time to
> the time it takes for each concatenation. That's why I talked about order
> of magnitude differences. If you look at the vast increase in time taken
> for concatenation when going from 10**5 to 10**6 iterations, that cannot
> be blamed on the char conversion.

True. string addition is O(n^2); the conversion time is O(n). But
fair's fair.

> At least, that's what it looks like to me -- I'm perplexed by the *vast*
> increase in speed in your version, far more than I would have predicted
> from pulling out the char conversion. I can think of three
> possibilities:

Everything got faster, so it wasn't just pulling the chr conversion.

> (1) Your PC is *hugely* faster than mine;

It's a 3Ghz P4.

> (2) Your value of x is a lot smaller than I was using (you don't actually
> say what x you use); or

It's still in the buffer, and I copied it from your timings:

>>> x = 100000

> (3) You are using a version and/or implementation of Python that has a
> different underlying implementation of string concatenation.

I'm runing Python 2.4.1 built with GCC 3.4.2.

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list