Skip to content

gh-92914: Round the allocated size for lists up to the even number #92915

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 19, 2022
Merged
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
7 changes: 4 additions & 3 deletions Lib/test/test_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1432,9 +1432,10 @@ def get_gen(): yield 1
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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Always round the allocated size for lists up to the nearest even number.
6 changes: 6 additions & 0 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down