本文介绍了字典访问速度比较与整数键对字符串键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大字典,我必须从中寻找价值观很多次。我的键是整数,但代表标签,所以不需要添加,减法等...我最终尝试评估字符串键和整数键字典之间的访问时间,这里是结果。

 从timeit导入计时器

Dint = dict()
Dstr = dict()

对于我在范围(10000)中:
Dint [i] = i
Dstr [str(i)] = i


打印' ,
打印(定时器(DOT中的7498,__main__ import Dint中的7498)timeit(100000000))
打印'Dint'中的int键,
print(Timer dint中的7498 in Dint,from __main__ import Dint)。timeit(100000000))
打印'Dstr'中的字符串键,
打印(Timer('Dod中的7498,__main__导入Dstr)timeit(100000000))
print'int key in Dstr',
print(Timer(7498 in Dstr,from __main__ import Dstr)timeit(100000000))

每次都会产生轻微的变化:

  STR键Dint 4.5552944017 
int键在Dint 7.14334390267
字符串键在Dstr中6.69923791116
int键在Dstr中5.03503126455

是否证明使用字符串作为键的字典比使用整数作为键更快?

解决方案

CPython的 dict 实际上实际上是针对字符串键查找进行了优化的。有两个不同的功能, lookdict lookdict_string lookdict_unicode 在Python 3中),可用于执行查找。 Python将使用字符串优化的版本,直到搜索非字符串数据,然后使用更一般的函数。您可以通过下载CPython的源代码并阅读 dictobject.c 来查看实际的实现。



由于当 dict 具有所有字符串键时,此优化查找更快。


I've got a large dictionary from which I have to look up for values a lot of times. My keys are integers but represent labels so do not need to be added, substracted, etc... I ended up trying to assess access time between string key and integer key dictionary and here is the result.

from timeit import Timer

Dint = dict()
Dstr = dict()

for i in range(10000):
    Dint[i] = i
    Dstr[str(i)] = i


print 'string key in Dint',
print(Timer("'7498' in Dint", "from __main__ import Dint").timeit(100000000))
print 'int key in Dint',
print(Timer("7498 in Dint", "from __main__ import Dint").timeit(100000000))
print 'string key in Dstr',
print(Timer("'7498' in Dstr", "from __main__ import Dstr").timeit(100000000))
print 'int key in Dstr',
print(Timer("7498 in Dstr", "from __main__ import Dstr").timeit(100000000))

which produces slight variations between runs reproduced each time :

string key in Dint 4.5552944017
int key in Dint 7.14334390267
string key in Dstr 6.69923791116
int key in Dstr 5.03503126455

Does it prove that using dictionary with strings as keys is faster to access than with integers as keys?

解决方案

CPython's dict implementation is in fact optimized for string key lookups. There are two different functions, lookdict and lookdict_string (lookdict_unicode in Python 3), which can be used to perform lookups. Python will use the string-optimized version until a search for non-string data, after which the more general function is used. You can look at the actual implementation by downloading CPython's source and reading through dictobject.c.

As a result of this optimization lookups are faster when a dict has all string keys.

这篇关于字典访问速度比较与整数键对字符串键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:52