Skip to content

Commit e59b1d3

Browse files
committed
gh-162782: Speed up set key comparison and hashing
Compare exact compact integers and strings directly when probing a locked set or inserting a key. Reuse cached string and tuple hashes and compute compact integer hashes inline.
1 parent d88a6b9 commit e59b1d3

3 files changed

Lines changed: 171 additions & 39 deletions

File tree

‎Lib/test/test_set.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,5 +2237,72 @@ def test_cuboctahedron(self):
22372237

22382238
#==============================================================================
22392239

2240+
class TestSetKeyOperations(unittest.TestCase):
2241+
def test_probe_mutation_during_eq(self):
2242+
class MutKey:
2243+
def __init__(self, value):
2244+
self.value = value
2245+
2246+
def __hash__(self):
2247+
return 1
2248+
2249+
def __eq__(self, other):
2250+
nonlocal mutate
2251+
if mutate is not None:
2252+
change, mutate = mutate, None
2253+
change()
2254+
return isinstance(other, MutKey) and self.value == other.value
2255+
2256+
mutate = None
2257+
for op in (operator.and_, operator.sub, operator.le):
2258+
for side in (0, 1):
2259+
with self.subTest(op=op, side=side):
2260+
a = {MutKey(i) for i in range(4)}
2261+
b = {MutKey(i) for i in range(2, 6)}
2262+
target = (a, b)[side]
2263+
mutate = lambda: target.update(range(100, 140))
2264+
result = op(a, b)
2265+
self.assertIsNone(mutate)
2266+
self.assertIsInstance(result, bool if op is operator.le
2267+
else set)
2268+
self.assertIn(139, target)
2269+
2270+
def test_frozenset_probe_with_mutating_eq(self):
2271+
class MutKey:
2272+
def __hash__(self):
2273+
return 1
2274+
2275+
def __eq__(self, other):
2276+
source.clear()
2277+
return isinstance(other, MutKey)
2278+
2279+
probe = frozenset([MutKey()])
2280+
source = {MutKey()}
2281+
self.assertTrue(source <= probe)
2282+
self.assertEqual(source, set())
2283+
2284+
def test_colliding_compact_ints(self):
2285+
self.assertEqual(hash(-1), hash(-2))
2286+
s = {-1, -2}
2287+
self.assertEqual(len(s), 2)
2288+
s.remove(-1)
2289+
self.assertNotIn(-1, s)
2290+
self.assertIn(-2, s)
2291+
s.add(-1)
2292+
s.remove(-2)
2293+
self.assertIn(-1, s)
2294+
self.assertNotIn(-2, s)
2295+
2296+
def test_mixed_numeric_keys(self):
2297+
for keys in itertools.permutations((True, 1, 1.0)):
2298+
s = {keys[0]}
2299+
s.add(keys[1])
2300+
self.assertIs(next(iter(s)), keys[0])
2301+
self.assertEqual(len(s), 1)
2302+
self.assertIn(keys[2], s)
2303+
s.remove(keys[2])
2304+
self.assertEqual(s, set())
2305+
2306+
22402307
if __name__ == "__main__":
22412308
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up set operations on exact integers and on strings and tuples with
2+
cached hashes.

‎Objects/setobject.c‎

Lines changed: 102 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
#include "pycore_ceval.h" // _PyEval_GetBuiltin()
3636
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION, Py_END_CRITICAL_SECTION
3737
#include "pycore_dict.h" // _PyDict_Contains_KnownHash()
38+
#include "pycore_long.h" // _PyLong_BothAreCompact()
3839
#include "pycore_modsupport.h" // _PyArg_NoKwnames()
3940
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
4041
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_SSIZE_RELAXED()
@@ -134,32 +135,58 @@ set_compare_threadsafe(PySetObject *so, setentry *table, setentry *ep,
134135

135136
#endif
136137

138+
/* Return 1 if equal, 0 if not, or -1 if the keys need a rich comparison. */
139+
static inline int
140+
set_keys_eq_fast(PyObject *a, PyObject *b)
141+
{
142+
if (PyLong_CheckExact(a) && PyLong_CheckExact(b)) {
143+
PyLongObject *x = (PyLongObject *)a;
144+
PyLongObject *y = (PyLongObject *)b;
145+
if (_PyLong_BothAreCompact(x, y)) {
146+
return _PyLong_CompactValue(x) == _PyLong_CompactValue(y);
147+
}
148+
}
149+
else if (PyUnicode_CheckExact(a) && PyUnicode_CheckExact(b)) {
150+
return unicode_eq(a, b);
151+
}
152+
return -1;
153+
}
154+
155+
static Py_NO_INLINE int
156+
set_compare_entry_slow(PySetObject *so, setentry *table, setentry *entry,
157+
PyObject *startkey, PyObject *key)
158+
{
159+
Py_INCREF(startkey);
160+
int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
161+
Py_DECREF(startkey);
162+
if (cmp < 0) {
163+
return SET_LOOKKEY_ERROR;
164+
}
165+
if (table != so->table || entry->key != startkey) {
166+
return SET_LOOKKEY_CHANGED;
167+
}
168+
return cmp;
169+
}
170+
137171
static inline Py_ALWAYS_INLINE int
138172
set_compare_entry_lock_held(PySetObject *so, setentry *table, setentry *entry,
139173
PyObject *key, Py_hash_t hash)
140174
{
141175
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(so);
142-
if (entry->hash == 0 && entry->key == NULL)
176+
if (entry->hash == 0 && entry->key == NULL) {
143177
return SET_LOOKKEY_EMPTY;
178+
}
144179
if (entry->hash == hash) {
145180
PyObject *startkey = entry->key;
146181
assert(startkey != dummy);
147-
if (startkey == key)
148-
return SET_LOOKKEY_FOUND;
149-
if (PyUnicode_CheckExact(startkey)
150-
&& PyUnicode_CheckExact(key)
151-
&& unicode_eq(startkey, key))
152-
return SET_LOOKKEY_FOUND;
153-
table = so->table;
154-
Py_INCREF(startkey);
155-
int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
156-
Py_DECREF(startkey);
157-
if (cmp < 0)
158-
return SET_LOOKKEY_ERROR;
159-
if (table != so->table || entry->key != startkey)
160-
return SET_LOOKKEY_CHANGED;
161-
if (cmp > 0)
182+
if (startkey == key) {
162183
return SET_LOOKKEY_FOUND;
184+
}
185+
int eq = set_keys_eq_fast(startkey, key);
186+
if (eq >= 0) {
187+
return eq;
188+
}
189+
return set_compare_entry_slow(so, table, entry, startkey, key);
163190
}
164191
return SET_LOOKKEY_NO_MATCH;
165192
}
@@ -277,23 +304,29 @@ set_add_entry_takeref(PySetObject *so, PyObject *key, Py_hash_t hash)
277304
if (entry->hash == hash) {
278305
PyObject *startkey = entry->key;
279306
assert(startkey != dummy);
280-
if (startkey == key)
307+
if (startkey == key) {
281308
goto found_active;
282-
if (PyUnicode_CheckExact(startkey)
283-
&& PyUnicode_CheckExact(key)
284-
&& unicode_eq(startkey, key))
285-
goto found_active;
286-
table = so->table;
287-
Py_INCREF(startkey);
288-
cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
289-
Py_DECREF(startkey);
290-
if (cmp > 0)
309+
}
310+
int eq = set_keys_eq_fast(startkey, key);
311+
if (eq > 0) {
291312
goto found_active;
292-
if (cmp < 0)
293-
goto comparison_error;
294-
if (table != so->table || entry->key != startkey)
295-
goto restart;
296-
mask = so->mask;
313+
}
314+
if (eq < 0) {
315+
table = so->table;
316+
Py_INCREF(startkey);
317+
cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
318+
Py_DECREF(startkey);
319+
if (cmp > 0) {
320+
goto found_active;
321+
}
322+
if (cmp < 0) {
323+
goto comparison_error;
324+
}
325+
if (table != so->table || entry->key != startkey) {
326+
goto restart;
327+
}
328+
mask = so->mask;
329+
}
297330
}
298331
else if (entry->hash == -1) {
299332
assert (entry->key == dummy);
@@ -342,6 +375,36 @@ set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
342375
return set_add_entry_takeref(so, Py_NewRef(key), hash);
343376
}
344377

378+
static inline Py_hash_t
379+
set_hash_key(PyObject *op)
380+
{
381+
if (PyUnicode_CheckExact(op)) {
382+
Py_hash_t h = PyUnstable_Unicode_GET_CACHED_HASH(op);
383+
if (h != -1) {
384+
return h;
385+
}
386+
}
387+
else if (PyLong_CheckExact(op)) {
388+
PyLongObject *v = (PyLongObject *)op;
389+
if (_PyLong_IsCompact(v)) {
390+
Py_hash_t h = _PyLong_CompactValue(v);
391+
if (h == -1) {
392+
h = -2;
393+
}
394+
assert(h == PyObject_Hash(op));
395+
return h;
396+
}
397+
}
398+
else if (PyTuple_CheckExact(op)) {
399+
PyTupleObject *v = (PyTupleObject *)op;
400+
Py_hash_t h = FT_ATOMIC_LOAD_SSIZE_RELAXED(v->ob_hash);
401+
if (h != -1) {
402+
return h;
403+
}
404+
}
405+
return PyObject_Hash(op);
406+
}
407+
345408
static void
346409
set_unhashable_type(PyObject *key)
347410
{
@@ -361,7 +424,7 @@ set_unhashable_type(PyObject *key)
361424
int
362425
_PySet_AddTakeRef(PySetObject *so, PyObject *key)
363426
{
364-
Py_hash_t hash = PyObject_Hash(key);
427+
Py_hash_t hash = set_hash_key(key);
365428
if (hash == -1) {
366429
set_unhashable_type(key);
367430
Py_DECREF(key);
@@ -600,7 +663,7 @@ set_discard_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
600663
static int
601664
set_add_key(PySetObject *so, PyObject *key)
602665
{
603-
Py_hash_t hash = PyObject_Hash(key);
666+
Py_hash_t hash = set_hash_key(key);
604667
if (hash == -1) {
605668
set_unhashable_type(key);
606669
return -1;
@@ -611,7 +674,7 @@ set_add_key(PySetObject *so, PyObject *key)
611674
static int
612675
set_contains_key(PySetObject *so, PyObject *key)
613676
{
614-
Py_hash_t hash = PyObject_Hash(key);
677+
Py_hash_t hash = set_hash_key(key);
615678
if (hash == -1) {
616679
set_unhashable_type(key);
617680
return -1;
@@ -622,7 +685,7 @@ set_contains_key(PySetObject *so, PyObject *key)
622685
static int
623686
set_discard_key(PySetObject *so, PyObject *key)
624687
{
625-
Py_hash_t hash = PyObject_Hash(key);
688+
Py_hash_t hash = set_hash_key(key);
626689
if (hash == -1) {
627690
set_unhashable_type(key);
628691
return -1;
@@ -1806,7 +1869,7 @@ set_intersection(PySetObject *so, PyObject *other)
18061869
}
18071870

18081871
while ((key = PyIter_Next(it)) != NULL) {
1809-
hash = PyObject_Hash(key);
1872+
hash = set_hash_key(key);
18101873
if (hash == -1)
18111874
goto error;
18121875
rv = set_contains_entry(so, key, hash);
@@ -2592,7 +2655,7 @@ _PySet_Contains(PySetObject *so, PyObject *key)
25922655
{
25932656
assert(so);
25942657

2595-
Py_hash_t hash = PyObject_Hash(key);
2658+
Py_hash_t hash = set_hash_key(key);
25962659
if (hash == -1) {
25972660
if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) {
25982661
set_unhashable_type(key);
@@ -2652,7 +2715,7 @@ static PyObject *
26522715
frozenset___contains___impl(PySetObject *so, PyObject *key)
26532716
/*[clinic end generated code: output=2301ed91bc3a6dd5 input=2f04922a98d8bab7]*/
26542717
{
2655-
Py_hash_t hash = PyObject_Hash(key);
2718+
Py_hash_t hash = set_hash_key(key);
26562719
if (hash == -1) {
26572720
if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) {
26582721
set_unhashable_type(key);
@@ -3117,7 +3180,7 @@ PySet_Contains(PyObject *anyset, PyObject *key)
31173180
}
31183181

31193182
PySetObject *so = (PySetObject *)anyset;
3120-
Py_hash_t hash = PyObject_Hash(key);
3183+
Py_hash_t hash = set_hash_key(key);
31213184
if (hash == -1) {
31223185
set_unhashable_type(key);
31233186
return -1;

0 commit comments

Comments
 (0)