Optimize slicing of bytes and bytearray by avoiding useless copying.

This restores the behavior that was present in Python 2.x.
This commit is contained in:
Alexandre Vassalotti 2009-04-03 06:38:02 +00:00
parent 1102062abb
commit e2641f45b6
2 changed files with 10 additions and 12 deletions

View File

@ -411,18 +411,18 @@ bytes_subscript(PyByteArrayObject *self, PyObject *index)
} }
else { else {
char *source_buf = PyByteArray_AS_STRING(self); char *source_buf = PyByteArray_AS_STRING(self);
char *result_buf = (char *)PyMem_Malloc(slicelength); char *result_buf;
PyObject *result; PyObject *result;
if (result_buf == NULL) result = PyByteArray_FromStringAndSize(NULL, slicelength);
return PyErr_NoMemory(); if (result == NULL)
return NULL;
result_buf = PyByteArray_AS_STRING(result);
for (cur = start, i = 0; i < slicelength; for (cur = start, i = 0; i < slicelength;
cur += step, i++) { cur += step, i++) {
result_buf[i] = source_buf[cur]; result_buf[i] = source_buf[cur];
} }
result = PyByteArray_FromStringAndSize(result_buf, slicelength);
PyMem_Free(result_buf);
return result; return result;
} }
} }

View File

@ -951,19 +951,17 @@ string_subscript(PyBytesObject* self, PyObject* item)
slicelength); slicelength);
} }
else { else {
source_buf = PyBytes_AsString((PyObject*)self); source_buf = PyBytes_AS_STRING(self);
result_buf = (char *)PyMem_Malloc(slicelength); result = PyBytes_FromStringAndSize(NULL, slicelength);
if (result_buf == NULL) if (result == NULL)
return PyErr_NoMemory(); return NULL;
result_buf = PyBytes_AS_STRING(result);
for (cur = start, i = 0; i < slicelength; for (cur = start, i = 0; i < slicelength;
cur += step, i++) { cur += step, i++) {
result_buf[i] = source_buf[cur]; result_buf[i] = source_buf[cur];
} }
result = PyBytes_FromStringAndSize(result_buf,
slicelength);
PyMem_Free(result_buf);
return result; return result;
} }
} }