Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve :class:`int` performance on 64-bit builds by allowing up to 60-bit ints,
which fit in existing spare space, to use the freelist.
23 changes: 19 additions & 4 deletions Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,17 @@ long_normalize(PyLongObject *v)
# define MAX_LONG_DIGITS ((INT64_MAX-1) / PyLong_SHIFT)
#endif

/* The freelist holds blocks of sizeof(PyLongObject) bytes: the padding
after ob_digit[0] can have space for more than one digit. */
#define MAX_DIGITS_FOR_FREELIST \
((Py_ssize_t)((sizeof(PyLongObject) - \
offsetof(PyLongObject, long_value.ob_digit)) / sizeof(digit)))

static PyLongObject *
long_alloc(Py_ssize_t size)
{
static_assert(MAX_DIGITS_FOR_FREELIST >= 1,
"int freelist blocks must hold at least one digit");
assert(size >= 0);
PyLongObject *result = NULL;
if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Expand All @@ -169,8 +177,13 @@ long_alloc(Py_ssize_t size)
* assume that there is always at least one digit present. */
Py_ssize_t ndigits = size ? size : 1;

if (ndigits == 1) {
Py_ssize_t alloc_digits = ndigits;
if (ndigits <= MAX_DIGITS_FOR_FREELIST) {
result = (PyLongObject *)_Py_FREELIST_POP(PyLongObject, ints);
/* The block may later go on the freelist and be reused for any
int with up to MAX_DIGITS_FOR_FREELIST digits, so allocate room
for that many digits, not just ndigits. */
alloc_digits = MAX_DIGITS_FOR_FREELIST;
}
if (result == NULL) {
/* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
Expand All @@ -179,7 +192,7 @@ long_alloc(Py_ssize_t size)
incorrect in the presence of padding between the header
and the digits. */
result = PyObject_Malloc(offsetof(PyLongObject, long_value.ob_digit) +
ndigits*sizeof(digit));
alloc_digits*sizeof(digit));
if (!result) {
PyErr_NoMemory();
return NULL;
Expand Down Expand Up @@ -3638,7 +3651,7 @@ _PyLong_ExactDealloc(PyObject *self)
_Py_SetImmortal(self);
return;
}
if (_PyLong_IsCompact((PyLongObject *)self)) {
if (_PyLong_DigitCount((PyLongObject *)self) <= MAX_DIGITS_FOR_FREELIST) {
_Py_FREELIST_FREE(ints, self, PyObject_Free);
return;
}
Expand All @@ -3658,7 +3671,9 @@ long_dealloc(PyObject *self)
_Py_SetImmortal(self);
return;
}
if (PyLong_CheckExact(self) && _PyLong_IsCompact((PyLongObject *)self)) {
if (PyLong_CheckExact(self)
&& _PyLong_DigitCount((PyLongObject *)self) <= MAX_DIGITS_FOR_FREELIST)
{
_Py_FREELIST_FREE(ints, self, PyObject_Free);
return;
}
Expand Down
Loading