Any problems with *lots* of attributes?
Aahz
aahz at pythoncraft.com
Thu Feb 5 08:49:55 EST 2004
In article <246a4e07.0402042327.5192034a at posting.google.com>,
Frank Millman <frank at chagford.com> wrote:
>Aahz <aahz at pythoncraft.com> wrote:
>>
>> OTOH, there's certainly nothing wrong with using dicts; they are the
>> single most fundamental Python data type after strings. (All Python
>> name/attribute access is built on top of dicts.)
>
>This is exactly my point, but I may be misunderstanding how it works
>internally. If I have a class with 20 attributes, it will have a
>dictionary with 20 entries. If I have hundreds of instances of the
>class, do I end up with hundreds of dictionaries (or the equivalent
>internal structures), and if so, does this not lead to memory bloat?
>If I store the data in a list, there will only be one dictionary entry
>per instance. On the other hand, I suppose there must be some reference
>to each of the elements of each list, so maybe there is an equivalent
>overhead. Is this a valid concern, or am I worrying about nothing?
You're mostly worrying about nothing; your analysis is essentially
correct.
> def getval_from_list(self):
> start = time()
> for i in xrange(1000000):
> aa = self.l[0]
> return (time() - start)
Try this instead:
def getval_from_list(self):
l = self.l
start = time()
for i in xrange(1000000):
aa = l[0]
return (time() - start)
Your original code pays the penalty for *both* dict/attribute lookup and
list lookup.
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
More information about the Python-list
mailing list