Python中set.discard和set.remove方法之间的运行时差异?

2022-01-17 00:00:00 python set

问题描述

这些方法的官方 Python 2.7 文档听起来几乎相同,与唯一的区别似乎是 remove() 会引发 KeyError 而 discard 不会.

我想知道这两种方法的执行速度是否存在差异.如果做不到这一点,它们之间是否有任何有意义的区别(除了 KeyError)?

解决方案

在一种情况下引发异常是一个非常有意义的区别.如果尝试从不存在的集合中删除元素会出错,则最好使用 set.remove() 而不是 set.discard().p>

这两种方法在实现上是相同的,除了相比 set_discard() set_remove()函数添加行:

if (rv == DISCARD_NOTFOUND) {set_key_error(key);返回空值;}

这会引发 KeyError.由于这需要更多的工作,set.remove() 比 teeniest 慢一点;您的 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.

相关文章