gh-92914: Round the allocated size for lists up to the even number (GH-92915)

(cherry picked from commit 8a6af5a346)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2022-06-14 12:16:21 -07:00 committed by GitHub
parent cbfbe248e3
commit 73c8f3ff54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 3 deletions

View File

@ -1432,9 +1432,10 @@ class SizeofTest(unittest.TestCase):
import re
check(re.finditer('',''), size('2P'))
# list
samples = [[], [1,2,3], ['1', '2', '3']]
for sample in samples:
check(list(sample), vsize('Pn') + len(sample)*self.P)
check(list([]), vsize('Pn'))
check(list([1]), vsize('Pn') + 2*self.P)
check(list([1, 2]), vsize('Pn') + 2*self.P)
check(list([1, 2, 3]), vsize('Pn') + 4*self.P)
# sortwrapper (list)
# XXX
# cmpwrapper (list)

View File

@ -0,0 +1 @@
Always round the allocated size for lists up to the nearest even number.

View File

@ -94,6 +94,12 @@ list_preallocate_exact(PyListObject *self, Py_ssize_t size)
assert(self->ob_item == NULL);
assert(size > 0);
/* Since the Python memory allocator has granularity of 16 bytes on 64-bit
* platforms (8 on 32-bit), there is no benefit of allocating space for
* the odd number of items, and there is no drawback of rounding the
* allocated size up to the nearest even number.
*/
size = (size + 1) & ~(size_t)1;
PyObject **items = PyMem_New(PyObject*, size);
if (items == NULL) {
PyErr_NoMemory();