]> granicus.if.org Git - python/commitdiff
Optimize slicing of bytes and bytearray by avoiding useless copying.
authorAlexandre Vassalotti <alexandre@peadrop.com>
Fri, 3 Apr 2009 06:38:02 +0000 (06:38 +0000)
committerAlexandre Vassalotti <alexandre@peadrop.com>
Fri, 3 Apr 2009 06:38:02 +0000 (06:38 +0000)
This restores the behavior that was present in Python 2.x.

Objects/bytearrayobject.c
Objects/bytesobject.c

index 428ee57a4d33ce247ff7adb6643502b99156a93d..fc1245208f2efbf40f2ebf7e5570b4a83601fe93 100644 (file)
@@ -411,18 +411,18 @@ bytes_subscript(PyByteArrayObject *self, PyObject *index)
         }
         else {
             char *source_buf = PyByteArray_AS_STRING(self);
-            char *result_buf = (char *)PyMem_Malloc(slicelength);
+            char *result_buf;
             PyObject *result;
 
-            if (result_buf == NULL)
-                return PyErr_NoMemory();
+            result = PyByteArray_FromStringAndSize(NULL, slicelength);
+            if (result == NULL)
+                return NULL;
 
+            result_buf = PyByteArray_AS_STRING(result);
             for (cur = start, i = 0; i < slicelength;
                  cur += step, i++) {
                      result_buf[i] = source_buf[cur];
             }
-            result = PyByteArray_FromStringAndSize(result_buf, slicelength);
-            PyMem_Free(result_buf);
             return result;
         }
     }
index a4a2e65777f60849be1ef0d9d92f6453022e6c6a..d3b598e0e8b6029265396058b4875a6365165282 100644 (file)
@@ -951,19 +951,17 @@ string_subscript(PyBytesObject* self, PyObject* item)
                                slicelength);
                }
                else {
-                       source_buf = PyBytes_AsString((PyObject*)self);
-                       result_buf = (char *)PyMem_Malloc(slicelength);
-                       if (result_buf == NULL)
-                               return PyErr_NoMemory();
+                       source_buf = PyBytes_AS_STRING(self);
+                       result = PyBytes_FromStringAndSize(NULL, slicelength);
+                       if (result == NULL)
+                               return NULL;
 
+                       result_buf = PyBytes_AS_STRING(result);
                        for (cur = start, i = 0; i < slicelength;
                             cur += step, i++) {
                                result_buf[i] = source_buf[cur];
                        }
 
-                       result = PyBytes_FromStringAndSize(result_buf,
-                                                           slicelength);
-                       PyMem_Free(result_buf);
                        return result;
                }
        }