Optimize ascii(str): don't encode/decode repr if repr is already ASCII

This commit is contained in:
Victor Stinner 2013-04-14 18:44:10 +02:00
parent 322cc7438c
commit af03757d20
2 changed files with 4 additions and 1 deletions

View File

@ -451,6 +451,9 @@ PyObject_ASCII(PyObject *v)
if (repr == NULL) if (repr == NULL)
return NULL; return NULL;
if (PyUnicode_IS_ASCII(repr))
return repr;
/* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace"); ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Py_DECREF(repr); Py_DECREF(repr);

View File

@ -6499,7 +6499,7 @@ _PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
return NULL; return NULL;
/* Fast path: if it is an ASCII-only string, construct bytes object /* Fast path: if it is an ASCII-only string, construct bytes object
directly. Else defer to above function to raise the exception. */ directly. Else defer to above function to raise the exception. */
if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128) if (PyUnicode_IS_ASCII(unicode))
return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode), return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
PyUnicode_GET_LENGTH(unicode)); PyUnicode_GET_LENGTH(unicode));
return unicode_encode_ucs1(unicode, errors, 128); return unicode_encode_ucs1(unicode, errors, 128);