Python中的dict.has_key和dict中的关键字之间的效率差异 [英] Efficiency difference between dict.has_key and key in dict in Python
问题描述
可能重复:
'has_key()'或'in'?
在Python有两种方式可以决定密钥
是否在 dict
中:
In Python, there're two ways of deciding whether a key
is in a dict
:
如果dict.has_key(key)
和如果在dict中键入
有人告诉我,第二个比第一个慢,因为关键字中的使得表达式在dict上是一个迭代,所以它将比
has_key
替代方案慢,这显然是使用散列来作出决定。
Someone tells me that the second one is slower than the first one since the in
keyword makes the expression an iteration over the dict, so it will be slower than the has_key
alternative, which apparently uses hash to make the decision.
我非常怀疑不同之处在于,由于我认为Python可以将关键字中的
在
dict
之前转换为某种哈希方式,没有找到关于这个的正式要求。
As I highly doubt the difference, since I think Python is smart enough to translate an in
keyword before a dict
to some hash way, I can't find any formal claim about this.
两者之间真的有任何效率差异吗?
So is there really any efficiency difference between the two?
感谢。
推荐答案
这两个操作都执行相同的操作:检查在dict中实现的哈希表。也不会迭代整个字典。请记住,在dict 中的x的与
关键字中的不同,如果在
中的x。他们都使用,但是是不同的操作。
Both of these operations do the same thing: examine the hash table implemented in the dict for the key. Neither will iterate the entire dictionary. Keep in mind that for x in dict
is different than if x in dict
. They both use the in
keyword, but are different operations.
关键字成为 dict的一个调用。dict .__包含__
,该dict可以实现,但它喜欢。
The in
keyword becomes a call on dict.__contains__
, which dict can implement however it likes.
如果这些操作的时间有差异,它将非常小,并且将与的函数调用开销有关对象的has_key
。
If there is a difference in the timings of these operations, it will be very small, and will have to do with the function call overhead of has_key
.
BTW,一般偏好在dict 中的键作为意图的更清晰的表达,而不是
dict.has_key(键)
。请注意,速度与偏好无关。可读性比速度更重要,除非您知道您处于关键路径。
BTW, the general preference is for key in dict
as a clearer expression of the intent than dict.has_key(key)
. Note that speed has nothing to do with the preference. Readability is more important than speed unless you know you are in the critical path.
这篇关于Python中的dict.has_key和dict中的关键字之间的效率差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!