]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42808: Add PyType_Type.tp_vectorcall for type(obj) performance (GH-24058)
authorDennis Sweeney <36520290+sweeneyde@users.noreply.github.com>
Mon, 22 Feb 2021 02:59:16 +0000 (21:59 -0500)
committerGitHub <noreply@github.com>
Mon, 22 Feb 2021 02:59:16 +0000 (11:59 +0900)
Misc/NEWS.d/next/Core and Builtins/2021-01-02-05-10-58.bpo-42808.AOxgxl.rst [new file with mode: 0644]
Objects/typeobject.c

diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-01-02-05-10-58.bpo-42808.AOxgxl.rst b/Misc/NEWS.d/next/Core and Builtins/2021-01-02-05-10-58.bpo-42808.AOxgxl.rst
new file mode 100644 (file)
index 0000000..1c70005
--- /dev/null
@@ -0,0 +1,2 @@
+Simple calls to ``type(object)`` are now faster due to the
+``vectorcall`` calling convention. Patch by Dennis Sweeney.
index 33a7872ecc45c6d83e9ae49cc468bb1fe7191f04..8b115220630adc112ff172d629432b6a3682eacd 100644 (file)
@@ -2888,6 +2888,23 @@ error:
     return NULL;
 }
 
+static PyObject *
+type_vectorcall(PyObject *metatype, PyObject *const *args,
+                 size_t nargsf, PyObject *kwnames)
+{
+    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
+    if (nargs == 1 && metatype == (PyObject *)&PyType_Type){
+        if (!_PyArg_NoKwnames("type", kwnames)) {
+            return NULL;
+        }
+        return Py_NewRef(Py_TYPE(args[0]));
+    }
+    /* In other (much less common) cases, fall back to
+       more flexible calling conventions. */
+    PyThreadState *tstate = PyThreadState_GET();
+    return _PyObject_MakeTpCall(tstate, metatype, args, nargs, kwnames);
+}
+
 /* An array of type slot offsets corresponding to Py_tp_* constants,
   * for use in e.g. PyType_Spec and PyType_GetSlot.
   * Each entry has two offsets: "slot_offset" and "subslot_offset".
@@ -3896,6 +3913,7 @@ PyTypeObject PyType_Type = {
     type_new,                                   /* tp_new */
     PyObject_GC_Del,                            /* tp_free */
     (inquiry)type_is_gc,                        /* tp_is_gc */
+    .tp_vectorcall = type_vectorcall,
 };