前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 字典遍历方法性能对比

python 字典遍历方法性能对比

作者头像
用户9127725
发布2022-08-08 08:27:20
4600
发布2022-08-08 08:27:20
举报
文章被收录于专栏:刘悦的技术博客

最近项目中使用到了dict的遍历,笔者写了几年的python,大多数都是使用dict.keys()的遍历方式。无奈项目执行过程中当dict中的元素上千万的时候,两层for循环性能实在是扛不住,于是测试了一下几种遍历方法的性能

import timeit

 DICT_SIZE = 5000

 testDict = dict()

 for i in range(DICT_SIZE):

     testDict[i] = i 

 assert len(testDict) == DICT_SIZE

 def test1():

     for k in testDict.keys():

        key = k 

        value = testDict[k]

 def test2():

    for k in testDict:

        key = k 

        value = testDict[k]

 def test3():

    for k in testDict.iterkeys():

        key = k 

        value = testDict[k]

 def test4():

    for k,v in testDict.items():

        key = k 

        value = v 

 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)

 print timeit.timeit("test4()", setup="from __main__ import test4", number=2000)

测试结果如下:

0.698087930679

0.643119812012

0.642452955246

0.88481593132

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012-02-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档