Skip to content

Commit 73c8f3f

Browse files
gh-92914: Round the allocated size for lists up to the even number (GH-92915)
(cherry picked from commit 8a6af5a) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent cbfbe24 commit 73c8f3f

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

Lib/test/test_sys.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1432,9 +1432,10 @@ def get_gen(): yield 1
14321432
import re
14331433
check(re.finditer('',''), size('2P'))
14341434
# list
1435-
samples = [[], [1,2,3], ['1', '2', '3']]
1436-
for sample in samples:
1437-
check(list(sample), vsize('Pn') + len(sample)*self.P)
1435+
check(list([]), vsize('Pn'))
1436+
check(list([1]), vsize('Pn') + 2*self.P)
1437+
check(list([1, 2]), vsize('Pn') + 2*self.P)
1438+
check(list([1, 2, 3]), vsize('Pn') + 4*self.P)
14381439
# sortwrapper (list)
14391440
# XXX
14401441
# cmpwrapper (list)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Always round the allocated size for lists up to the nearest even number.

Objects/listobject.c

+6
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,12 @@ list_preallocate_exact(PyListObject *self, Py_ssize_t size)
9494
assert(self->ob_item == NULL);
9595
assert(size > 0);
9696

97+
/* Since the Python memory allocator has granularity of 16 bytes on 64-bit
98+
* platforms (8 on 32-bit), there is no benefit of allocating space for
99+
* the odd number of items, and there is no drawback of rounding the
100+
* allocated size up to the nearest even number.
101+
*/
102+
size = (size + 1) & ~(size_t)1;
97103
PyObject **items = PyMem_New(PyObject*, size);
98104
if (items == NULL) {
99105
PyErr_NoMemory();

0 commit comments

Comments
 (0)