Runtime difference between set.discard and set.remove methods in Python?

狂风中的少年 提交于 2019-12-18 02:51:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27850073/runtime-difference-between-set-discard-and-set-remove-methods-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!