Runtime difference between set.discard and set.remove methods in Python?(Python中set.discard和set.remove方法之间的运行时差异?)
问题描述
这些方法的官方 Python 2.7 文档听起来几乎相同,与唯一的区别似乎是 remove() 会引发 KeyError 而 discard 不会.
我想知道这两种方法的执行速度是否存在差异.如果做不到这一点,它们之间是否有任何有意义的区别(除了 KeyError)?
在一种情况下引发异常是一个非常有意义的区别.如果尝试从不存在的集合中删除元素会出错,则最好使用 set.remove() 而不是 p>set.discard().
这两种方法在实现上是相同的,除了相比 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.
这篇关于Python中set.discard和set.remove方法之间的运行时差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中set.discard和set.remove方法之间的运行时差异?
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
