只需运行下面的测试,发现填充OrderedDict()
的速度比填充dict()
或list()
慢一个数量级。
为什么呢?
# list()
In [1]: timeit test_list()
1000 loops, best of 3: 298 us per loop
# dict()
In [3]: timeit test_dict()
1000 loops, best of 3: 269 us per loop
# dict()
In [3]: timeit test_ord_dict()
100 loops, best of 3: 1.77 ms per loop
使用:
def test_ord_dict():
a = OrderedDict()
for el in xrange(1000):
a[el] = np.random.randint(100)
return a
def test_dict():
a = dict()
for el in xrange(1000):
a[el] = np.random.randint(100)
return a
def test_list():
a = list()
for el in xrange(1000):
a.append(np.random.randint(100))
return a
答案 0 :(得分:5)
OrderedDict
是用纯Python实现的,所以这里是源代码的相关部分:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value)
如果密钥不存在,您将创建一个新列表并从列表中访问两个项目,这将减慢速度。
答案 1 :(得分:3)
有两个原因:
根据定义,OrderedDict
必须比dict
做更多的工作。
(更重要的是)OrderedDict
是written in Python,而dict
和list
是用C语言写的。