syntax from diveintopython

Mark Pilgrim f8dy at yahoo.com
Wed Apr 18 10:28:56 EDT 2001


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message
news:s32D6.5145$sk3.1514222 at newsb.telia.net...
> Mark Pilgrim wrote:
> > Other than using string.join(..., "") instead of "".join(...) -- a topic
> > which has been beaten to death recently on this newsgroup and which I
> > address explicitly in my book
> > (http://diveintopython.org/odbchelper_join.html) -- how would you
rewrite
> > this?
>
> but it's still buggy: if an attribute value contains a reserved
> character (a character entity), it will produce bogus output.

OK, that's an obscure case that I hadn't ever encountered (and I actually
use this script as part of building my site), but you're right.  Given that,
using locals() is out of the question, at least within the list
comprehension.

Given your claim that your version was twice as fast, I did some timing
tests of my own.

>     def unknown_starttag(self, tag, attrs):
>         append = self.parts.append
>         append("<" + tag)
>         for k, v in attrs:
>             append(" %s='%s'" % (k, cgi.escape(v)))
>         append(">")

To my surprise, this variant works just as fast for 1 attribute and faster
for 2 attributes or more:

    def unknown_starttag(self, tag, attrs):
        strattrs = "".join([' %s="%s"' % (k, cgi.escape(v)) for k, v in
attrs])
        rc.append('<' + tag + strattrs + '>')

To my added surprise, this variant is SLOWER than either of the above:

    def unknown_starttag(self, tag, attrs):
        strattrs = "".join([' %s="%s"' % (k, cgi.escape(v)) for k, v in
attrs])
        rc.append('<%s%s>' % (tag, strattrs))

The only difference is the last line, using string formatting instead of the
+ operator.  I was under the impression that the + operator for string
concatenation was slower than string formatting because Python had to
construct several intermediate strings in memory.  Is that true?  Why is +
faster in this case?  Is it generally faster, or am I doing something
obviously wrong here?

Puzzled,
-M






More information about the Python-list mailing list