Skip to content

gh-162350: Add AC vectorcall for method.__new__ to speed up types.MethodType - #162408

Merged
cmaloney merged 4 commits into
python:mainfrom
tanloong:methodtype_vectorcall
Nov 22, 2026
Merged

cmaloney merged 4 commits into
python:mainfrom
tanloong:methodtype_vectorcall

Conversation

@tanloong

@tanloong tanloong commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Add @vectorcall to Argument Clinic to generate method.__new__. Rename method_new as method_type_new to avoid the AC generated verctorcall name conflicting with existing method_vectorcall. Didn't add Py_TPFLAGS_IMMUTABLETYPE as this flag automatically applies to static types.

Performance before:

Constructor microbenchmark (best of 7, 1000000 iterations each)
MethodType(f, obj)                   0.1073 s     107.3 ns/op
types.MethodType(f, obj)             0.1142 s     114.2 ns/op
MethodType(C.m, obj)                 0.1224 s     122.4 ns/op
call bound method m()                0.0944 s      94.4 ns/op

Performance after:

Constructor microbenchmark (best of 7, 1000000 iterations each)
MethodType(f, obj)                   0.0805 s      80.5 ns/op  (24.97% faster)
types.MethodType(f, obj)             0.0862 s      86.2 ns/op  (24.51% faster)
MethodType(C.m, obj)                 0.0927 s      92.7 ns/op  (24.26% faster)
call bound method m()                0.0946 s      94.6 ns/op  (-0.21% faster)
Benchmark script
import timeit

SETUP = """
import sys
import types
from types import MethodType

def f(self):
    pass

class C:
    def m(self):
        pass

obj = C()
m = MethodType(f, obj)
"""

CASES = [
    ("MethodType(f, obj)", "MethodType(f, obj)"),
    ("types.MethodType(f, obj)", "types.MethodType(f, obj)"),
    ("MethodType(C.m, obj)", "MethodType(C.m, obj)"),
    ("call bound method m()", "m()"),
]

NUMBER = 1_000_000
REPEAT = 7

print("Constructor microbenchmark (best of %d, %d iterations each)" % (REPEAT, NUMBER))
for name, stmt in CASES:
    times = timeit.repeat(stmt=stmt, setup=SETUP, number=NUMBER, repeat=REPEAT)
    best = min(times)
    print("%-34s %8.4f s   %7.1f ns/op" % (name, best, best / NUMBER * 1e9))

Comment thread Objects/classobject.c Resolved
@cmaloney
cmaloney merged commit cffc305 into python:main Nov 22, 2026
102 of 103 checks passed
@tanloong
tanloong deleted the methodtype_vectorcall branch November 22, 2026 08:12
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.

2 participants