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

miss-islington webhook-mailer at python.org
Tue Jun 14 15:16:25 EDT 2022


https://github.com/python/cpython/commit/73c8f3ff545742132e95b076fa7cea5ca41904fd
commit: 73c8f3ff545742132e95b076fa7cea5ca41904fd
branch: 3.11
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2022-06-14T12:16:21-07:00
summary:

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

(cherry picked from commit 8a6af5a34642f5564220eb50d72caada8f17fc78)

Co-authored-by: Serhiy Storchaka <storchaka at gmail.com>

files:
A Misc/NEWS.d/next/Core and Builtins/2022-05-18-08-32-33.gh-issue-92914.tJUeTD.rst
M Lib/test/test_sys.py
M Objects/listobject.c

diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
index 87ff4a2deb593..26e0f2082ea2f 100644
--- a/Lib/test/test_sys.py
+++ b/Lib/test/test_sys.py
@@ -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)
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-05-18-08-32-33.gh-issue-92914.tJUeTD.rst b/Misc/NEWS.d/next/Core and Builtins/2022-05-18-08-32-33.gh-issue-92914.tJUeTD.rst
new file mode 100644
index 0000000000000..1242a15c029dc
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2022-05-18-08-32-33.gh-issue-92914.tJUeTD.rst	
@@ -0,0 +1 @@
+Always round the allocated size for lists up to the nearest even number.
diff --git a/Objects/listobject.c b/Objects/listobject.c
index b50623ed73d94..0a99ec919b8c8 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -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();



More information about the Python-checkins mailing list