← 输入框|github.com|刷新
Skip to content

gh-162350: Add AC vectorcall for collections.defaultdict - #162820

Open
tanloong wants to merge 1 commit into
python:mainfrom
tanloong:defaultdict_vectorcall
Open

tanloong wants to merge 1 commit into
python:mainfrom
tanloong:defaultdict_vectorcall

Conversation

@tanloong

@tanloong tanloong commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Replace hand-written defdict_init with AC + vectorcall. There is no bad arguments message change.

For argument default_factory: dd->default_factory = Py_NewRef(default_factory) cretes strong reference before result = PyDict_Type.tp_init(self, newargs, kwargs) runs arbitrary code. For args and kwargs: defdict_vectorcall() already creates strong references for both before calling defdict_init_impl().

The default_factory argument defaults to None, so defaultdict() is functionally equivalent to defaultdict(None), thus AC declaration uses default_factory: object = None. It should not add (c_default="NULL") as that causes error at the default_factory != Py_None check, thus didn't use default_factory: object(c_default="NULL") = None.

Benchmark:

+-------------------------+--------+----------------------+
| Benchmark               | main   | patch                |
+=========================+========+======================+
| defaultdict()           | 146 ns | 110 ns: 1.33x faster |
+-------------------------+--------+----------------------+
| defaultdict(list)       | 169 ns | 118 ns: 1.43x faster |
+-------------------------+--------+----------------------+
| defaultdict(list, kw)   | 239 ns | 168 ns: 1.42x faster |
+-------------------------+--------+----------------------+
| defaultdict(list, **kw) | 286 ns | 358 ns: 1.25x slower |
+-------------------------+--------+----------------------+
| Geometric mean          | (ref)  | 1.21x faster         |
+-------------------------+--------+----------------------+
Details
import pyperf

SETUP = """
from collections import defaultdict

kw = {'a': 1, 'b': 2}
"""

CASES = [
    ('defaultdict()', 'defaultdict()'),
    ('defaultdict(list)', 'defaultdict(list)'),
    ('defaultdict(list, kw)', 'defaultdict(list, kw)'),
    ('defaultdict(list, **kw)', 'defaultdict(list, **kw)')
]

runner = pyperf.Runner()
for name, stmt in CASES:
    runner.timeit(name, stmt=stmt, setup=SETUP)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant