get-a-cup-of-coffee slow

Jeff Shannon jeff at ccvcorp.com
Fri Aug 10 19:00:59 EDT 2001


Courageous wrote:

> >Why is the first one so slow?
>
> Because you're duplicating the entire string every time you add
> a single character to it. A similar situation arises in Java; one should
> use a StringBuffer object instead. In Python this can be accomplished
> by appending chars to the end of a list and then stringifying it: no
> StringBuffer needed.
>
> C//

You might also look into the cStringIO module, which, from what I've heard,
is something similar to Java's StringBuffer (I don't do Java, so can't
verify this).  StringIO builds a string using a file-like interface, and
maintains an internal buffer so that you *can* do multiple appends without
the huge overhead of copying strings every time.  And it probably even has a
quick way write to a real file.  (Note: cStringIO is a C implementation,
StringIO is a Python version; cStringIO is faster, but StringIO can be
subclassed.)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list