https://github.com/python/cpython/commit/b5aa1954277494d80e83b7642f633b53e12e3579
commit: b5aa1954277494d80e83b7642f633b53e12e3579
branch: main
author: Victor Stinner <[email protected]>
committer: vstinner <[email protected]>
date: 2026-10-02T17:51:47+02:00
summary:

gh-155742: Use PyMem_Malloc() in memoryview.hex() (#158582)

Replace PyBytesWriter with a simple PyMem_Malloc(), since no bytes
object is needed. PyMem_Malloc() should be more efficient in this
case.

files:
M Objects/memoryobject.c

diff --git a/Objects/memoryobject.c b/Objects/memoryobject.c
index 5a8ae6ad149a75..e6d49b6c29a3e9 100644
--- a/Objects/memoryobject.c
+++ b/Objects/memoryobject.c
@@ -2468,22 +2468,19 @@ memoryview_hex_impl(PyMemoryViewObject *self, PyObject 
*sep,
         return ret;
     }
 
-    PyBytesWriter *writer = PyBytesWriter_Create(src->len);
-    if (writer == NULL) {
+    char *buffer = PyMem_Malloc(src->len);
+    if (buffer == NULL) {
+        PyErr_NoMemory();
         return NULL;
     }
 
-    if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
-                              src, src->len, 'C') < 0) {
-        PyBytesWriter_Discard(writer);
+    if (PyBuffer_ToContiguous(buffer, src, src->len, 'C') < 0) {
+        PyMem_Free(buffer);
         return NULL;
     }
 
-    PyObject *ret = _Py_strhex_with_sep(
-        PyBytesWriter_GetData(writer),
-        PyBytesWriter_GetSize(writer),
-        sep, bytes_per_sep);
-    PyBytesWriter_Discard(writer);
+    PyObject *ret = _Py_strhex_with_sep(buffer, src->len, sep, bytes_per_sep);
+    PyMem_Free(buffer);
 
     return ret;
 }

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to