Trivial performance questions

Michael Hudson mwh at python.net
Fri Oct 17 09:17:23 EDT 2003


"Brian Patterson" <bp at computastore.com> writes:

> I have noticed in the book of words that hasattr works by calling
> getattr and raising an exception if no such attribute exists.  If I
> need the value in any case, am I better off using getattr within a
> try statement myself, or is there some clever implementation
> enhancement which makes this a bad idea?
> 
> i.e. should I prefer:
>     if hasattr(self,"datum"):
>         datum=getattr("datum")
>     else:
>         datum=None
>         self.datum=None
> 
> over:
>     try:
>         datum=self.getattr("datum")
>     except:

Don't do that, do "except AttributeError:" instead.

>         self.datum=None
>         datum=None
> 
> The concept of deliberately raising an error is still foreign to
> this python newbie, but I really like the trapping facilities.  I
> just worry about the performance implications and memory usage of
> such things, especially since I'm writing for Zope.

The answer to which of these runs the fastest depends on how often you
expect the attribute to exist.  If it's not that often, the first form
will probably be quicker, if not the second.

However, there's a third form:

    datum = getattr(self, "datum", None)

which is what you want here.

> And while I'm here:  Is there a difference in performance when checking:
>     datum is None
> over:
>     datum == None

Yes (I think...), but you shouldn't care much about it.

> and similarly:
>     if x is None or y is None:
> or:
>     if None in (x,y):

Pass.  Time it if you really care (my bet's on the former being
quicker).

> I appreciate that these are trivial in the extreme, but I seem to be
> writing dozens of them, and I may as well use the right one and
> squeeze what performance I can.

This is an unhelpful attitude.  You're writing in Python after all!

If profile shows some of this code to be a hotspot, *then* and only
then is it an appropriate time to worry about such trivial performance
gains.

Cheers,
mwh

-- 
  The only problem with Microsoft is they just have no taste.
              -- Steve Jobs, (From _Triumph of the Nerds_ PBS special)
                                and quoted by Aahz on comp.lang.python




More information about the Python-list mailing list