Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Optimize set difference_update for the case when the other set is much
larger than the base set. (Suggested by Evgeny Kapun with code contributed
by Michele Orrù).
18 changes: 17 additions & 1 deletion Objects/setobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1463,9 +1463,25 @@ set_difference_update_internal(PySetObject *so, PyObject *other)
setentry *entry;
Py_ssize_t pos = 0;

/* Optimization: When the other set is more than 8 times
larger than the base set, replace the other set with
interesection of the two sets.
*/
if ((PySet_GET_SIZE(other) >> 3) > PySet_GET_SIZE(so)) {
other = set_intersection(so, other);
if (other == NULL)
return -1;
} else {
Py_INCREF(other);
}

while (set_next((PySetObject *)other, &pos, &entry))
if (set_discard_entry(so, entry->key, entry->hash) < 0)
if (set_discard_entry(so, entry->key, entry->hash) < 0) {
Py_DECREF(other);
return -1;
}

Py_DECREF(other);
} else {
PyObject *key, *it;
it = PyObject_GetIter(other);
Expand Down