[Tutor] Style question with classes and modules

Tino Dai tinoloc at gmail.com
Thu Jul 19 22:06:42 CEST 2007


On 7/19/07, Eric Brunson <brunson at brunson.com> wrote:
>
> Tino Dai wrote:
> > On 7/19/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>>
> > wrote:
> >
> >     > The two advantages that I can see are, I don't need to type as
> >     much, and
> >     > there would be a speed up in the execution of code.
> >
> >     Why do you expect a speedup?
> >
> >
> > In the  Python  Reference by David Beazley on p. 40, he substituted
> > import math
> > with from math import sqrt and he switched out d = d + math.sqrt(i) with
> > sqrt(i). He said that that change made the program run twice as fast.
> > So therefore
> > I was under the impression that "from somemodule import someclass"
> > would always be
> > faster than import somemodule.
>
> The reason it's faster is because to get the actual function for
> math.sqrt() after importing math, you have to do a dictionary lookup in
> the "math" namespace.  I don't think it should run twice as fast.  I
> would only worry about it if you had some situation where you were using
> the same name over and over:
>
> import math
> for i in range( 0, 1000000000 ):
>     x = math.sqrt(i)
>
> That's 1000000000 dictionary lookups.  Importing just the sqrt name
> would avoid those lookups, so would:
>
> import math
> f = math.sqrt
> for i in range( 0, 1000000000 ):
>    x = f(i)
>
> Does that make sense?


I guess there is no silver bullet. Thanks for that!  It makes total sense
now that you mention it.

-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070719/454ce78c/attachment.html 


More information about the Tutor mailing list