Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
caching attribute reference
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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
Reply
#3
It doesn't matter. Both references are pointers to one memory address
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
It doesn't technically matter, but you may find style reasons.
Reply
#5
I agree with that. If it's more convenient
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
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.
Reply
#7
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')
        ...
Reply
#8
There's no class method there though, they're all instance methods.
Reply
#9
Yes, Of coarse you're correct.
Reply
#10
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,553 Sep-07-2020, 08:02 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020