From e6091f8a356fbd1ea348b0915c110dbfc6bbb129 Mon Sep 17 00:00:00 2001 From: Dong-hee Na Date: Mon, 9 Jan 2023 00:52:06 +0900 Subject: [PATCH] gh-81381: Reduce allcoated size of PyType_GenericAlloc if possible --- .../2023-01-09-00-55-03.gh-issue-81381.21bU3z.rst | 2 ++ Objects/typeobject.c | 11 +++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2023-01-09-00-55-03.gh-issue-81381.21bU3z.rst diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-01-09-00-55-03.gh-issue-81381.21bU3z.rst b/Misc/NEWS.d/next/Core and Builtins/2023-01-09-00-55-03.gh-issue-81381.21bU3z.rst new file mode 100644 index 00000000000000..a9e9b4f207c8ef --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-01-09-00-55-03.gh-issue-81381.21bU3z.rst @@ -0,0 +1,2 @@ +Reduce the extra allocation size of :c:func:`PyType_GenericAlloc` except the +type is if a subtype of 'type'. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index f2d78cf50913ec..2fc791ecdb6fa1 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -1289,9 +1289,12 @@ PyObject * _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems) { PyObject *obj; - const size_t size = _PyObject_VAR_SIZE(type, nitems+1); - /* note that we need to add one, for the sentinel */ - + size_t extra = 0; + if (type->tp_flags & Py_TPFLAGS_TYPE_SUBCLASS || type->tp_flags & Py_TPFLAGS_HAVE_VECTORCALL) { + /* note that we need to add one, for the sentinel */ + extra = 1; + } + const size_t size = _PyObject_VAR_SIZE(type, nitems + extra); const size_t presize = _PyType_PreHeaderSize(type); char *alloc = PyObject_Malloc(size + presize); if (alloc == NULL) { @@ -1309,7 +1312,7 @@ _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems) _PyObject_Init(obj, type); } else { - _PyObject_InitVar((PyVarObject *)obj, type, nitems); + _PyObject_InitVar((PyVarObject *)obj, type, nitems + extra); } return obj; }