A question on python performance.
Joe Goldthwaite
joe at goldthwaites.com
Thu Sep 27 17:56:03 EDT 2007
chris.monsanto at gmail.com wrote:
>Makes perfect sense to me! Think about it:
>
>method 1: looks up the method directly from the object (fastest)
>method 2: looks up __class__, then looks up __dict__, then gets the
>element from __dict__
>method 3: looks up caller, looks up __class__, looks up __dict__, gets
>element from __dict__
>
>To get the element directly from the object (method 1), Python has to
>internally check __class__.__dict__[element], which shows why method 1
>and method 2 are nearly the same speed. The last version has to look
>up caller in addition to the process described by method 2.
>
>The best way to do what you are doing:
>
>getattr(self, param)(self, *args)
I didn't know about the getattr function. I tried to search for that
type of function but not knowing how to word the search request,
I couldn't find it. That's a lot cleaner way of doing what I was
trying to do. I benchmarked it and it's so close in speed to the
hard-coded method as to be identical.
Paul Hankin wrote:
>You're calling a function (getValue) that just calls a method of trend
>(caller), that just calls another method of trend (Ptd or Qtd or ...).
>You can skip all these steps, and just call the method yourself: the
>code that calls getValue(trend, param, per) replace with
>trend.<something>(per) if you're calling getValue with a static value
>for param, or getattr(trend, param)(per) if param is dynamic.
You're right, it makes sense. Thanks for also pointing out the getattr
function.
Eric Jones wrote:
>What you're describing is a case of mulitple dispatch. See http://
www.artima.com/weblogs/viewpost.jsp?thread=101605 for a short
>description and (as short) example by Guido. You can probably fill
>that out and adapt it to your needs. Alternatively, you could look
>into the multimethods module in the Gnosis Utilities package: http://
>pypi.python.org/pypi/Gnosis_Utils/1.2.1-a
Thanks Eric. I read that article on multi-methods but I can't say I
really understand it. I guess I still think of decorators as the people
who got the gym ready for the prom. I've tried getting up to speed on
decorators but I haven't had much success. Like I mentioned previously,
with Python, I still feel like a newbie.
Bruno Desthuilliers wrote:
>IOW, direct access to obj.__class__.__dict__ bypasses both inheritence
>and per-instance overriding.
Thanks for your response also Bruno. I don't understand the code you
posted well enough yet to even ask a useful question. There are a number
of things I haven't seen before. Now I really feel like a newbie!
I'm working on it though so I may have some questions later.
Thanks again for everyone's input. I really appreciate it.
More information about the Python-list
mailing list