gh-126868: Add freelist for compact ints to `_PyLong_New` (#128181)

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
This commit is contained in:
Pieter Eendebak 2024-12-26 16:17:22 +01:00 committed by GitHub
parent fb0b94223d
commit 3bd7730bbd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 12 deletions

View File

@ -0,0 +1 @@
Increase usage of freelist for :class:`int` allocation.

View File

@ -156,7 +156,7 @@ PyLongObject *
_PyLong_New(Py_ssize_t size)
{
assert(size >= 0);
PyLongObject *result;
PyLongObject *result = NULL;
if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
PyErr_SetString(PyExc_OverflowError,
"too many digits in integer");
@ -165,6 +165,11 @@ _PyLong_New(Py_ssize_t size)
/* Fast operations for single digit integers (including zero)
* assume that there is always at least one digit present. */
Py_ssize_t ndigits = size ? size : 1;
if (ndigits == 1) {
result = (PyLongObject *)_Py_FREELIST_POP(PyLongObject, ints);
}
if (result == NULL) {
/* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
sizeof(digit)*size. Previous incarnations of this code used
sizeof() instead of the offsetof, but this risks being
@ -176,8 +181,9 @@ _PyLong_New(Py_ssize_t size)
PyErr_NoMemory();
return NULL;
}
_PyLong_SetSignAndDigitCount(result, size != 0, size);
_PyObject_Init((PyObject*)result, &PyLong_Type);
}
_PyLong_SetSignAndDigitCount(result, size != 0, size);
/* The digit has to be initialized explicitly to avoid
* use-of-uninitialized-value. */
result->long_value.ob_digit[0] = 0;