Do more imported objects affect performance

Nick Craig-Wood nick at craig-wood.com
Mon Dec 1 06:30:44 EST 2008


Rafe <rafesacks at gmail.com> wrote:
>  On Dec 1, 7:26?am, "Filip Gruszczy?ski" <grusz... at gmail.com> wrote:
> > I have following question: if I use
> >
> > from module import *
> >
> > instead
> >
> > from module import Class
> >
> > am I affecting performance of my program? I believe, that all those
> > names must be stored somewhere, when they are imported and then
> > browsed when one of them is called. So am I putting a lot of "garbage"
> > to this storage and make those searches longer?
> 
>  Why use it if you don't need it? Your post implies a choice and the
>  '*' import can really make things muddy if it isn't actually necessary
>  (rare). Why not just import the module and use what you need? It is
>  way easier to read/debug and maintains the name-space.

Importing the module is actualy slower...  If you import the name into
your namespace then there is only one lookup to do.  If you import the
module there are two.

$ python -m timeit -s 'from timeit import Timer' 'Timer'
10000000 loops, best of 3: 0.0784 usec per loop

$ python -m timeit -s 'import timeit' 'timeit.Timer'
1000000 loops, best of 3: 0.243 usec per loop

I'm not suggestion you should ever use "from module import *" only
ever import the things you actually need, eg
"from module import MyClass, my_function"

And here is the test again, actually calling something with the same
difference in execution speed :-

$ python -m timeit -s 'from os import nice' 'nice(0)'
1000000 loops, best of 3: 1.21 usec per loop

$ python -m timeit -s 'import os' 'os.nice(0)'
1000000 loops, best of 3: 1.48 usec per loop

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list