get-a-cup-of-coffee slow

Skip Montanaro skip at pobox.com
Thu Aug 9 18:45:45 EDT 2001


    Grant> Why is the first one so slow?  I assume it has to do with
    Grant> repeatedly appending characters to a string.  If so, is it
    Grant> because "s +=" is implemented as "s = s +", where the new one is
    Grant> always an appended copy of the original?  (I guess I would hope
    Grant> that in the case of a string "+=" operation, Python would leave a
    Grant> little spare space at the end of the new string so multiple
    Grant> appends would not have to make a copy with _each_ append.)

Repeat the mantra: "strings are immutable, strings are immutable, strings
are immutable". ;-)

    Grant> Also, I tried writing something like this with a list (which are
    Grant> presumably more suited to being appended), but then I realized
    Grant> that I didn't know how to write the contents of a list to a file
    Grant> as a stream of bytes.  There's probably a simple way to do that:
    Grant> what is it?

    >>> l = ["abc", "def", "@", "NOSPAM", ".foo", ".org"]
    >>> s = "".join(l)
    >>> print s
    abcdef at NOSPAM.foo.org

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list