Class optimization at runtime

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Mon Aug 2 23:21:03 CEST 2004


Larry Bates wrote:

> Kind of hard to tell what you are trying to accomplish
> but I'll try.  Define the class with no if/else statements.
> They only get parsed once.  It is the "class instance"
> creations that may get created millions of times.  They
> will be inside your logical structure.

Yup.

> class Foo:
>     def __init__(self):
>         # do stuff
> 
> class Bar:
>     def __init__(self):
>         # do stuff
> 
> if option: x=Foo()
> else:      x=Bar()

I don't see anything wrong with his original suggestion, provided that
makes the rest of the code simpler:

>> class Foo:
>>     if option:
>>         def __init__:
>>             #do stuff
>>     else:
>>         def __init__:
>>             #do other stuff

That 'if' also gets run only once - when the class is created.

Note that if your class instances only have a few instance variables,
the most effective optimization may be something quite else:  To make
them subclasses of 'object', and define __slots__.  A program of mine
ran in about half the time after doing so.  There are a number of
dangers involved with __slots__, though.  Check the reference manual.

For other optimization hints, see section 1.5 of the Python Programming
FAQ at <http://www.python.org/doc/faq/programming.html>.

-- 
Hallvard



More information about the Python-list mailing list