Search code examples
pythonperformancelanguage-features

Is it inefficient to access a python class member container in a loop statement?


I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables to use inside the loop.

My question is about the loop statement itself... if I have the following class:

class A(object):
   def __init__(self)
       self.myList = [ 'a','b','c', 'd', 'e' ]

Does the following code in a member function incur one, or one-per-loop-iteration (5) dictionary lookups?

for letter in self.myList:
     print letter

IE, should I adopt the following pattern, if I am concerned about efficiency...

localList = self.myList
for letter in localList:
    print letter

or is that actually LESS efficient due to the local variable assign?

Note, I am aware that early optimization is a dangerous pitfall if I'm concerned about the overall efficiency of code development. Here I am specifically asking about the efficiency of the code, not the coding.


Solution

  • An iterator is created from self.myList, and that iterator is used. No other extra lookups are done on self for the iteration.