[Python-Dev] OT: Performance vs. Clarity vs. Convention

Patrick K. O'Brien pobrien@orbtech.com
Wed, 5 Jun 2002 19:24:25 -0500

Forgive me if this is slightly off-topic for this list, but since we've been
talking about migration guides and coding idioms and tweaking performance
and such, I've got a few questions I'd like to ask.

I'll start with an actual code sample. This is a very simple class that's
part of an xhtml toolkit I'm writing.

class Comment:

    def __init__(self, content=''):
        self.content = content

    def __call__(self, content=''):
        o = self.__class__(content)
        return str(o)

    def __str__(self):
        return '<!-- %s -->' % self.content

    def __repr__(self):
        return repr(self.__str__())

When I look at this, I see certain decisions I've made and I'm wondering if
I've made the best decisions. I'm wondering how to balance performance
against clarity and proper coding conventions.

1. In the __call__ I save a reference to the object. Instead, I could

       return str(self.__class__(content))

Is there much of a performance impact by explicitly naming intermediate
references? (I need some of Tim Peter's performance testing scripts.)

2. I chose the slightly indirect str(o) instead of o.__str__(). Is this
slower? Is one style preferred over the other and why?

3. I used a format string, '<!-- %s -->' % self.content, where I could just
as easily have concatenated '<!-- ' + self.content + ' -->' instead. Is one
faster than the other?

4. Is there any documentation that covers these kinds of issues where there
is more than one way to do something? I'd like to have some foundation for
making these decisions. As you can probably guess, I usually hate having
more than one way to do anything. ;-)

Patrick K. O'Brien