Skip to content

Commit 6f6e38f

Browse files
authored
gh-161524: Speed up copying sparse dictionaries (#161636)
1 parent 21f63a8 commit 6f6e38f

4 files changed

Lines changed: 137 additions & 51 deletions

File tree

‎Lib/test/test_capi/test_watchers.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,27 @@ def test_set_existing_item(self):
5656
self.assert_events(["mod:foo:baz"])
5757

5858
def test_clone(self):
59+
sparse = {str(i): i for i in range(100)}
60+
for i in range(99):
61+
del sparse[str(i)]
62+
for d2 in ({"foo": "bar"}, sparse):
63+
d = {}
64+
with self.watcher() as wid:
65+
self.watch(wid, d)
66+
d.update(d2)
67+
self.assert_events(["clone"])
68+
self.assertEqual(d, d2)
69+
70+
def test_no_clone_event_on_allocation_failure(self):
71+
source = {1: 1, 2: 2}
72+
del source[1]
5973
d = {}
60-
d2 = {"foo": "bar"}
6174
with self.watcher() as wid:
6275
self.watch(wid, d)
63-
d.update(d2)
64-
self.assert_events(["clone"])
76+
with self.assertRaises(MemoryError):
77+
_testcapi.call_with_nomemory(0, 1, d.update, source)
78+
self.assert_events([])
79+
self.assertEqual(d, {})
6580

6681
def test_no_event_if_not_watched(self):
6782
d = {}

‎Lib/test/test_dict.py‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -465,17 +465,32 @@ class A:
465465
self.assertEqual(gc.is_tracked(d), gc.is_tracked(d2))
466466

467467
def test_copy_noncompact(self):
468-
# Dicts don't compact themselves on del/pop operations.
469-
# Copy will use a slow merging strategy that produces
470-
# a compacted copy when roughly 33% of dict is a non-used
471-
# keys-space (to optimize memory footprint).
472-
# In this test we want to hit the slow/compacting
473-
# branch of dict.copy() and make sure it works OK.
474-
d = {k: k for k in range(1000)}
475-
for k in range(950):
476-
del d[k]
477-
d2 = d.copy()
478-
self.assertEqual(d2, d)
468+
# Dicts don't compact themselves on del/pop operations. Check
469+
# copying a sparse table with both unicode and generic keys.
470+
class Key(CustomHash):
471+
hash_calls = 0
472+
473+
def __hash__(self):
474+
self.hash_calls += 1
475+
return super().__hash__()
476+
477+
for keys in ([str(i) for i in range(100)],
478+
[Key(i % 5) for i in range(100)]):
479+
with self.subTest(key_type=type(keys[0])):
480+
d = dict(zip(keys, range(100)))
481+
for i, key in enumerate(keys):
482+
if i not in (1, 51, 98):
483+
del d[key]
484+
expected = list(d.items())
485+
if isinstance(keys[0], Key):
486+
calls = [key.hash_calls for key in d]
487+
copies = (d.copy(), dict(d), {**d}, frozendict(d))
488+
if isinstance(keys[0], Key):
489+
self.assertEqual([key.hash_calls for key in d], calls)
490+
for copy in copies:
491+
self.assertEqual(list(copy.items()), expected)
492+
for key, value in expected:
493+
self.assertEqual(copy[key], value)
479494

480495
@support.nomemtest
481496
def test_copy_empty_no_memory(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up copying dictionaries with many deleted entries by copying live
2+
entries directly into a compact table instead of inserting them one by one.

‎Objects/dictobject.c‎

Lines changed: 91 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4296,6 +4296,60 @@ PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
42964296
return dict_merge_from_seq2(d, seq2, override);
42974297
}
42984298

4299+
4300+
/* Copy only live entries from a combined table, preserving insertion order.
4301+
The source is locked while its keys and values are referenced. */
4302+
static PyDictKeysObject *
4303+
dict_copy_keys(PyDictObject *orig)
4304+
{
4305+
assert(PyAnyDict_Check(orig));
4306+
assert(Py_TYPE(orig)->tp_iter == dict_iter);
4307+
assert(orig->ma_values == NULL);
4308+
assert(orig->ma_used > 0);
4309+
if (!PyFrozenDict_Check(orig)) {
4310+
ASSERT_DICT_LOCKED(orig);
4311+
}
4312+
4313+
PyDictKeysObject *oldkeys = orig->ma_keys;
4314+
Py_ssize_t used = orig->ma_used;
4315+
int unicode = DK_IS_UNICODE(oldkeys);
4316+
PyDictKeysObject *keys = new_keys_object(estimate_log2_keysize(used),
4317+
unicode);
4318+
if (keys == NULL) {
4319+
return NULL;
4320+
}
4321+
4322+
if (unicode) {
4323+
PyDictUnicodeEntry *src = DK_UNICODE_ENTRIES(oldkeys);
4324+
PyDictUnicodeEntry *dst = DK_UNICODE_ENTRIES(keys);
4325+
for (Py_ssize_t i = 0; i < used; i++) {
4326+
while (src->me_value == NULL) {
4327+
src++;
4328+
}
4329+
dst[i] = *src++;
4330+
Py_INCREF(dst[i].me_key);
4331+
Py_INCREF(dst[i].me_value);
4332+
}
4333+
build_indices_unicode(keys, dst, used);
4334+
}
4335+
else {
4336+
PyDictKeyEntry *src = DK_ENTRIES(oldkeys);
4337+
PyDictKeyEntry *dst = DK_ENTRIES(keys);
4338+
for (Py_ssize_t i = 0; i < used; i++) {
4339+
while (src->me_value == NULL) {
4340+
src++;
4341+
}
4342+
dst[i] = *src++;
4343+
Py_INCREF(dst[i].me_key);
4344+
Py_INCREF(dst[i].me_value);
4345+
}
4346+
build_indices_generic(keys, dst, used);
4347+
}
4348+
keys->dk_nentries = used;
4349+
keys->dk_usable -= used;
4350+
return keys;
4351+
}
4352+
42994353
static int
43004354
dict_dict_merge(PyDictObject *mp, PyDictObject *other, int override, PyObject **dupkey)
43014355
{
@@ -4308,32 +4362,35 @@ dict_dict_merge(PyDictObject *mp, PyDictObject *other, int override, PyObject **
43084362
/* a.update(a) or a.update({}); nothing to do */
43094363
return 0;
43104364
if (mp->ma_used == 0) {
4311-
/* Since the target dict is empty, _PyDict_Contains_KnownHash()
4312-
* always returns 0. Setting override to 1
4313-
* skips the unnecessary test.
4314-
*/
4315-
override = 1;
4316-
PyDictKeysObject *okeys = other->ma_keys;
4317-
4318-
// If other is clean, combined, and just allocated, just clone it.
4319-
if (mp->ma_values == NULL &&
4320-
other->ma_values == NULL &&
4321-
other->ma_used == okeys->dk_nentries &&
4322-
(DK_LOG_SIZE(okeys) == PyDict_LOG_MINSIZE ||
4323-
USABLE_FRACTION(DK_SIZE(okeys)/2) < other->ma_used)
4324-
) {
4325-
_PyDict_NotifyEvent(PyDict_EVENT_CLONED, mp, (PyObject *)other, NULL);
4326-
PyDictKeysObject *keys = clone_combined_dict_keys(other);
4365+
// Copy a combined table directly, compacting deleted entries.
4366+
if (mp->ma_values == NULL && other->ma_values == NULL) {
4367+
PyDictKeysObject *okeys = other->ma_keys;
4368+
PyDictKeysObject *keys;
4369+
if (other->ma_used == okeys->dk_nentries &&
4370+
(DK_LOG_SIZE(okeys) == PyDict_LOG_MINSIZE ||
4371+
USABLE_FRACTION(DK_SIZE(okeys)/2) < other->ma_used)) {
4372+
keys = clone_combined_dict_keys(other);
4373+
}
4374+
else {
4375+
keys = dict_copy_keys(other);
4376+
}
43274377
if (keys == NULL)
43284378
return -1;
43294379

4380+
_PyDict_NotifyEvent(PyDict_EVENT_CLONED, mp, (PyObject *)other, NULL);
43304381
ensure_shared_on_resize(mp);
43314382
dictkeys_decref(mp->ma_keys, IS_DICT_SHARED(mp));
43324383
set_keys(mp, keys);
4333-
STORE_USED(mp, other->ma_used);
4384+
STORE_USED(mp, keys->dk_nentries);
43344385
ASSERT_CONSISTENT(mp);
43354386
return 0;
43364387
}
4388+
4389+
/* Since the target dict is empty, _PyDict_Contains_KnownHash()
4390+
* always returns 0. Setting override to 1
4391+
* skips the unnecessary test.
4392+
*/
4393+
override = 1;
43374394
}
43384395
/* Do one big resize at the start, rather than
43394396
* incrementally resizing as we insert new items. Expect
@@ -4619,25 +4676,29 @@ copy_lock_held_untracked(PyObject *o, int as_frozendict)
46194676
return (PyObject *)split_copy;
46204677
}
46214678

4622-
if (Py_TYPE(mp)->tp_iter == dict_iter &&
4623-
mp->ma_values == NULL &&
4624-
(mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
4625-
{
4679+
if (Py_TYPE(mp)->tp_iter == dict_iter) {
46264680
/* Use fast-copy if:
46274681
46284682
(1) type(mp) doesn't override tp_iter; and
46294683
4630-
(2) 'mp' is not a split-dict; and
4684+
(2) 'mp' is not a split-dict.
46314685
4632-
(3) if 'mp' is non-compact ('del' operation does not resize dicts),
4633-
do fast-copy only if it has at most 1/3 non-used keys.
4686+
Dicts don't compact themselves on del/pop operations, so a large
4687+
dict can have very few live entries. Previously, fast-copy was
4688+
restricted to tables with at most 1/3 non-used entries; otherwise
4689+
PyDict_Merge produced a compacted copy.
46344690
4635-
The last condition (3) is important to guard against a pathological
4636-
case when a large dict is almost emptied with multiple del/pop
4637-
operations and copied after that. In cases like this, we defer to
4638-
PyDict_Merge, which produces a compacted copy.
4691+
Clone tables with few deleted entries as-is. For sparse tables,
4692+
copy only live entries into a compact table instead of retaining
4693+
deleted slots or reinserting entries one by one.
46394694
*/
4640-
PyDictKeysObject *keys = clone_combined_dict_keys(mp);
4695+
PyDictKeysObject *keys;
4696+
if (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3) {
4697+
keys = clone_combined_dict_keys(mp);
4698+
}
4699+
else {
4700+
keys = dict_copy_keys(mp);
4701+
}
46414702
if (keys == NULL) {
46424703
return NULL;
46434704
}
@@ -4668,14 +4729,7 @@ copy_lock_held_untracked(PyObject *o, int as_frozendict)
46684729
}
46694730
if (copy == NULL)
46704731
return NULL;
4671-
int res;
4672-
if (Py_TYPE(mp)->tp_iter == dict_iter) {
4673-
res = dict_dict_merge((PyDictObject *)copy, mp, 1, NULL);
4674-
}
4675-
else {
4676-
res = dict_merge(copy, o, 1, NULL);
4677-
}
4678-
if (res < 0) {
4732+
if (dict_merge(copy, o, 1, NULL) < 0) {
46794733
Py_DECREF(copy);
46804734
return NULL;
46814735
}

0 commit comments

Comments
 (0)