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

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2010-03-19T23:56:59Z Indexed on 2010/03/20 0:01 UTC
Read the original article Hit count: 188

Hi there.

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.

Thanks in advance!

D

© Stack Overflow or respective owner

Related posts about python

Related posts about efficiency