再进行大量数据处理时,常需要使用字典,并且将数据载入字典中
常用的三种字典元素添加方式有
=
update
setdefault
再单个元素添加时,这三种方法在性能上几乎没有区别,但在大量数据下还是存在一些差别
*这次性能测试采用time模块,初始为空字典,添加元素相同,测试一种后将字典清零,并将五次测试平均
import time #time模块
book_dict = {} #字典
单个方式验证格式如下
n=0
while n < 1000000 :
测试函数
n+=1
# clear方法,删除所有
book_dict.clear()
代码总览
#字典添加测试
import time
book_dict = {}
start = time.time()
n=0
while n < 1000000 :
book_dict["owner"] = "tyson"
n+=1
# clear方法,删除所有
book_dict.clear()
end = time.time()
print('用时 %6.3f' % (end - start))
start = time.time()
n=0
while n < 1000000 :
book_dict.update({"owner" :"tyson"})
n+=1
# clear方法,删除所有
book_dict.clear()
end = time.time()
print('用时 %6.3f' % (end - start))
start = time.time()
n=0
while n < 1000000 :
book_dict.setdefault("owner", "tyson")
n+=1
book_dict.clear()
end = time.time()
print('用时 %6.3f' % (end - start))
1 | 2 | 3 | 4 | 5 | 平均 |
---|---|---|---|---|---|
1.2156322 | 1.11661315 | 0.965009928 | 0.905605793 | 1.018309116 | 1.044234037 |
1.951138973 | 1.919217587 | 1.559949875 | 1.85595727 | 2.041434526 | 1.865539646 |
1.629626513 | 1.582581997 | 1.432097912 | 2.065351725 | 1.790330648 | 1.699997759 |
由此得出"="的性能最佳