Hi all I was wondering about the performance comparison of either using a dictionary or an object for a large collection of "things". Therefore I have run the attached test. I create a dictionary and an object. Both get the same number of items/attributes, respectively. Then, for both the values are read often (iterations).
Here are the results: attributes 100 iterations 1000000 dic 25.515999794 obj 138.570000172 Is the test meaningful and are you surprised by the results? I am, actually, because I would have assumed that attribute access with an object should be faster because lookup can be precompiled. kind regards Andre
import time import random ITERATIONS = 1000000 ATTRIBUTES = 100 class O(object): pass class Test(object): def __init__(self): self.attributes = [] self.dic = {} self.obj = O() for i in range(ATTRIBUTES): value = "" for s in range(12): value = value + chr(random.randint(ord('a'), ord('z'))) # print value attr = "" for s in range(6): attr = attr + chr(random.randint(ord('a'), ord('z'))) # print attr self.attributes.append(attr) self.dic[attr] = value self.obj.__setattr__(attr, value) print "attributes", len(self.attributes) def run_dic(self): t0 = time.time() for i in range(ITERATIONS): for a in self.attributes: v = self.dic[a] # print i, v t1 = time.time() return t1 - t0 def run_obj(self): t0 = time.time() for i in range(ITERATIONS): for a in self.attributes: v = self.obj.__getattribute__(a) # print i, v t1 = time.time() return t1 - t0 print "iterations", ITERATIONS t = Test() td = t.run_dic() to = t.run_obj() print "dic", td print "obj", to
-- http://mail.python.org/mailman/listinfo/python-list