来源:
方法一:直接遍历 速度快
for key in _dict: pass
方法二:iterkeys() 速度快
for _ in testDict.iterkeys(): pass
方法三:keys() 速度慢 因为keys()须要形成一个列表,构建一个列表对于一个大的dict开销是很大的。
for _ in testDict.keys(): pass
时间对比:
import timeitDICT_SIZE = 100*10000testDict = dict()for i in range(DICT_SIZE): testDict[i] = i # 构建大小为100W的字典assert len(testDict) == DICT_SIZEdef test1(): for _ in testDict.keys(): passdef test2(): for _ in testDict: passdef test3(): for _ in testDict.iterkeys(): pass# 分别测试2K次print timeit.timeit("test1()", setup="from __main__ import test1", number=2000) print timeit.timeit("test2()", setup="from __main__ import test2", number=2000)print timeit.timeit("test3()", setup="from __main__ import test3", number=2000)
输出
54.199467776430.266067575931.3075812315是windows + python 2.7的结果