Efficient string concatenation methods

Oliver Crow ocrow at skymind.com
Sun May 2 13:54:44 EDT 2004


Peter Hansen <peter at engcorp.com> wrote in message news:<s8OdnbvjBMT-ygndRVn-iQ at powergate.ca>...
> You left out the StringIO module (having done only the cStringIO
> version of that).

I should probably add that one just for reference. I left it out
originally because my instinct was that it would perform less well
than the string += operator.  I think it uses ordinary immutable
python strings for internal storage.

> Note also that, for any of the ones which do method calls,
> you can speed up the call by saving a reference to the
> bound method in a local variable.  For example, in method 4
> you can do "app_list = str_list.append" and then use
> "app_list(`num`)" instead of str_list.append(`num`).  This
> saves an attribute lookup on each loop iteration.  It's
> not "idiomatic" to do so except in (a) cases of optimization
> obsession, or (b) benchmarks. ;-)

I hadn't thought of this, although it makes sense.  It looks like I
could do this in methods 3, 4 and 5.  But I also feel that it makes
the code a little less readable.

I think the unstated goal I had was to find a method that could be
learned by python programmers and used in real programs without having
to think *too* hard about the various performance trade-offs.  So, in
that spirit I should definitely measure the difference, but perhaps
not go so far as to recommend it as part of the best overall approach.

> Interesting and useful results.  Thanks! :-)

Thanks!
Oliver



More information about the Python-list mailing list