_pickle: Optimize raw_unicode_escape(), use directly a bytes object, don't use

a temporary bytearray object.
This commit is contained in:
Victor Stinner 2014-08-17 21:14:46 +02:00
parent 88d146b7b9
commit 7270b7f1aa
1 changed files with 9 additions and 10 deletions

View File

@ -2050,7 +2050,7 @@ save_bytes(PicklerObject *self, PyObject *obj)
static PyObject * static PyObject *
raw_unicode_escape(PyObject *obj) raw_unicode_escape(PyObject *obj)
{ {
PyObject *repr, *result; PyObject *repr;
char *p; char *p;
Py_ssize_t i, size, expandsize; Py_ssize_t i, size, expandsize;
void *data; void *data;
@ -2069,13 +2069,14 @@ raw_unicode_escape(PyObject *obj)
if (size > PY_SSIZE_T_MAX / expandsize) if (size > PY_SSIZE_T_MAX / expandsize)
return PyErr_NoMemory(); return PyErr_NoMemory();
repr = PyByteArray_FromStringAndSize(NULL, expandsize * size); repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
if (repr == NULL) if (repr == NULL)
return NULL; return NULL;
if (size == 0) if (size == 0)
goto done; return repr;
assert(Py_REFCNT(repr) == 1);
p = PyByteArray_AS_STRING(repr); p = PyBytes_AS_STRING(repr);
for (i=0; i < size; i++) { for (i=0; i < size; i++) {
Py_UCS4 ch = PyUnicode_READ(kind, data, i); Py_UCS4 ch = PyUnicode_READ(kind, data, i);
/* Map 32-bit characters to '\Uxxxxxxxx' */ /* Map 32-bit characters to '\Uxxxxxxxx' */
@ -2104,12 +2105,10 @@ raw_unicode_escape(PyObject *obj)
else else
*p++ = (char) ch; *p++ = (char) ch;
} }
size = p - PyByteArray_AS_STRING(repr); size = p - PyBytes_AS_STRING(repr);
if (_PyBytes_Resize(&repr, size) < 0)
done: return NULL;
result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(repr), size); return repr;
Py_DECREF(repr);
return result;
} }
static int static int