Inverse of int(s, base)?

Steve dippyd at yahoo.com.au
Tue May 11 23:48:53 EDT 2004


Paul Rubin wrote:
> Oliver Fromme <olli at secnetix.de> writes:
> 
>>Is creating strings really that expensive in Python?  I'm
>>surpised that you're saying that modifying a list and then
>>calling reverse() and join() is more efficient.  I thought
>>that the overhead of compound objects such as lists is
>>more expensive than creating strings, which I thought where
>>rather "cheap and simple".
> 
> 
> Actually, for these int conversions (unless they're large long ints)
> it's no big deal.  The concern is when you're building up a long
> string (say, a 10 kilobyte html page) by concatenating a lot of short
> strings.  When you say "a = a + b" the cost is proportional to
> len(a+b), since that many chars must get copied around.  In the
> extreme case, suppose you build up a 10k web page one character at a
> time:
[snip]

This is a good time to remind newbies that the root of 
all evil lies in premature optimization (attributed to 
Donald Knuth).

You could do worse than read Guido's anecdote:
http://www.python.org/doc/essays/list2str.html

Then, read Joel's discussion of "Shlemiel the painter's 
algorithm":
http://www.joelonsoftware.com/articles/fog0000000319.html

And an example of it here:
http://lambda.weblogs.com/discuss/msgReader$3130
(see one of the last reader's comments)

In conclusion: if you are absolutely positive that you 
are only going to be adding together a few short 
strings, then you gain much readability by just adding 
together short strings. But if you are going to be 
adding together lots of long strings, use lists and 
only convert to a string at the end.

-- 
Steven D'Aprano





More information about the Python-list mailing list