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

The official Python 2.7 docs for these methods sound almost the same, with the only difference being that remove () raises a KeyError and then doesn’t.

I am wondering if there is a difference in execution speed between the two methods. Otherwise, is there any significant difference (KeyError ban) between them?

+6
source share
1 answer

Raising the exception in one case is a pretty significant difference. If you are trying to remove an element from a set that is not there, there will be an error, it is better to use set.remove() rather than set.discard() .

Both methods are identical in implementation, except that, compared to set_discard() function adds strings:

 if (rv == DISCARD_NOTFOUND) { set_key_error(key); return NULL; } 

A KeyError occurs. Since this is a bit more work, set.remove() is the lower faction slower; Your processor must perform one additional test before returning. But if your algorithm is dependent on an exception, then an additional branching test is unlikely to matter.

+16
source

Source: https://habr.com/ru/post/980731/


All Articles