Optimize repr(str): use _PyUnicode_FastCopyCharacters() when no character is escaped

This commit is contained in:
Victor Stinner 2013-04-14 18:45:39 +02:00
parent af03757d20
commit 55c08781e8

View file

@ -11968,7 +11968,7 @@ unicode_repr(PyObject *unicode)
Py_ssize_t isize;
Py_ssize_t osize, squote, dquote, i, o;
Py_UCS4 max, quote;
int ikind, okind;
int ikind, okind, unchanged;
void *idata, *odata;
if (PyUnicode_READY(unicode) == -1)
@ -11979,7 +11979,7 @@ unicode_repr(PyObject *unicode)
/* Compute length of output, quote characters, and
maximum character */
osize = 2; /* quotes */
osize = 0;
max = 127;
squote = dquote = 0;
ikind = PyUnicode_KIND(unicode);
@ -12010,7 +12010,9 @@ unicode_repr(PyObject *unicode)
}
quote = '\'';
unchanged = (osize == isize);
if (squote) {
unchanged = 0;
if (dquote)
/* Both squote and dquote present. Use squote,
and escape them */
@ -12018,6 +12020,7 @@ unicode_repr(PyObject *unicode)
else
quote = '"';
}
osize += 2; /* quotes */
repr = PyUnicode_New(osize, max);
if (repr == NULL)
@ -12027,7 +12030,12 @@ unicode_repr(PyObject *unicode)
PyUnicode_WRITE(okind, odata, 0, quote);
PyUnicode_WRITE(okind, odata, osize-1, quote);
if (unchanged) {
_PyUnicode_FastCopyCharacters(repr, 1,
unicode, 0,
isize);
}
else {
for (i = 0, o = 1; i < isize; i++) {
Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
@ -12105,6 +12113,7 @@ unicode_repr(PyObject *unicode)
}
}
}
}
/* Closing quote already added at the beginning */
assert(_PyUnicode_CheckConsistency(repr, 1));
return repr;