Python Forum
caching attribute reference - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: caching attribute reference (/thread-2128.html)

Pages: 1 2 3


caching attribute reference - Skaperen - Feb-21-2017

in a class method, i need to access an instance attribute, such as self.foo and use that value many times.  is there any expected performance benefit to caching it in a local variable, such as doing foo = self.foo, and using just foo instead of self.foo for all the uses?  if i modify it i could do foo = whatever or foo += somenumber then finish with self.foo = foo.


RE: caching attribute reference - Larz60+ - Feb-21-2017

I don't know if it's considered good practice, but I do it often
Usually in graphics applications when I have to do a lot with the parent widget


RE: caching attribute reference - wavic - Feb-21-2017

It doesn't matter. Both references are pointers to one memory address


RE: caching attribute reference - Larz60+ - Feb-21-2017

It doesn't technically matter, but you may find style reasons.


RE: caching attribute reference - wavic - Feb-21-2017

I agree with that. If it's more convenient


RE: caching attribute reference - micseydel - Feb-21-2017

I'm confused, if it's a class method, how does it get an instance? Is it a singleton? If not, how do you identify which instance?

If you want to modify it, I suggest not caching it, since it would make it slightly more likely to accidentally modify the cached one instead of the correct one. We shouldn't bother with performance improvements like this unless we've run the code and find it necessary.


RE: caching attribute reference - Larz60+ - Feb-21-2017

Here's an example (untested) of what I believe he is talking about
class GUI:
    def __init__(self, root=None):
        self = root
        ...
        self.method1()
        self.method2()

    def method1(self):
        r = self.root ...
        widget1(r, ...)
        widget2(r, ...)

    def method2(self):
        Label(self,root, text='xxxxx')
        ...



RE: caching attribute reference - micseydel - Feb-21-2017

There's no class method there though, they're all instance methods.


RE: caching attribute reference - Larz60+ - Feb-21-2017

Yes, Of coarse you're correct.


RE: caching attribute reference - Skaperen - Feb-22-2017

it might come down to the CPU cost of .attribute vs a plain local variable.  given that self is a local variable there is already the cost of accessing self.  now add on the cost of accessing an attribute within it ... unless python does any performance optimizing for self specifically (because it is so commonly used) or for repeating expressions.