Python 中 set.discard 和 set.remove 方法之间的运行时差异? [英] Runtime difference between set.discard and set.remove methods in Python?
问题描述
这些方法的官方 Python 2.7 文档 听起来几乎相同,但唯一的区别似乎是 remove() 引发 KeyError 而 discard 不会.
我想知道这两种方法的执行速度是否存在差异.否则,它们之间是否有任何有意义的区别(除了 KeyError)?
在一种情况下引发异常是一个非常有意义的差异.如果试图从一个不存在的集合中删除一个元素会出错,你最好使用 set.remove()
而不是 set.discard()
.>
这两种方法在实现上是相同的,只是与set_discard()
set_remove()
函数添加行:
if (rv == DISCARD_NOTFOUND) {set_key_error(key);返回空;}
这会引发 KeyError
.由于这需要更多的工作,set.remove()
比 最小 慢一点;在返回之前,您的 CPU 必须进行一项额外的测试.但是如果你的算法依赖于异常,那么额外的分支测试就没什么意义了.
The official Python 2.7 docs for these methods sounds nearly identical, with the sole difference seeming to be that remove() raises a KeyError while discard does not.
I'm wondering if there is a difference in execution speed between these two methods. Failing that, is there any meaningful difference (barring KeyError) between them?
Raising an exception in one case is a pretty meaningful difference. If trying to remove an element from a set that is not there would be an error, you better use set.remove()
rather than set.discard()
.
The two methods are identical in implementation, except that compared to set_discard()
the set_remove()
function adds the lines:
if (rv == DISCARD_NOTFOUND) {
set_key_error(key);
return NULL;
}
This raises the KeyError
. As this is slightly more work, set.remove()
is a teeniest fraction slower; your CPU has to do one extra test before returning. But if your algorithm depends on the exception then the extra branching test is hardly going to matter.
这篇关于Python 中 set.discard 和 set.remove 方法之间的运行时差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!