# HG changeset patch # User Fredrik Lundh # Date 1257421232 -3600 # Node ID 3d923899b532b8d445243597d1e68cc074c71cf8 # Parent 0ddfacbb25718c396f98e3fff5498b7c979020a3 Handle printable ASCII before checking for non-ASCII encodings, for a tiny speedup. diff -r 0ddfacbb25718c396f98e3fff5498b7c979020a3 -r 3d923899b532b8d445243597d1e68cc074c71cf8 cjson.c --- a/cjson.c Thu Nov 05 12:23:35 2009 +0100 +++ b/cjson.c Thu Nov 05 12:40:32 2009 +0100 @@ -577,6 +577,8 @@ c = op->ob_sval[i]; if (c == quote || c == '\\') *p++ = '\\', *p++ = c; + else if (c >= ' ' && c < 0x7f) + *p++ = c; else if (c == '\t') *p++ = '\\', *p++ = 't'; else if (c == '\n') @@ -587,15 +589,14 @@ *p++ = '\\', *p++ = 'f'; else if (c == '\b') *p++ = '\\', *p++ = 'b'; - else if (c < ' ' || c >= 0x7f) { + else { + /* Escape everything else. */ /* For performance, we don't want to call * PyOS_snprintf here (extra layers of * function call). */ sprintf(p, "\\u%04x", c & 0xff); p += 6; } - else - *p++ = c; } assert(newsize - (p - PyString_AS_STRING(v)) >= 1); *p++ = quote; @@ -647,9 +648,12 @@ if ((ch == (Py_UNICODE) PyString_AS_STRING(repr)[0] || ch == '\\')) { *p++ = '\\'; *p++ = (char) ch; - continue; } + /* Check for ASCII first */ + else if (ch >= ' ' && ch < 0x7F) + *p++ = (char) ch; + #ifdef Py_UNICODE_WIDE /* Map 21-bit characters to '\U00xxxxxx' */ else if (ch >= 0x10000) { @@ -702,7 +706,7 @@ } /* Map 16-bit characters to '\uxxxx' */ - if (ch >= 256) { + else if (ch >= 256) { *p++ = '\\'; *p++ = 'u'; *p++ = hexdigit[(ch >> 12) & 0x000F]; @@ -734,7 +738,7 @@ } /* Map non-printable US ASCII to '\u00hh' */ - else if (ch < ' ' || ch >= 0x7F) { + else { *p++ = '\\'; *p++ = 'u'; *p++ = '0'; @@ -742,10 +746,6 @@ *p++ = hexdigit[(ch >> 4) & 0x000F]; *p++ = hexdigit[ch & 0x000F]; } - - /* Copy everything else as-is */ - else - *p++ = (char) ch; } *p++ = PyString_AS_STRING(repr)[0]; @@ -1014,10 +1014,10 @@ } else if (object == Py_None) { return PyString_FromString("null"); } else if (PyString_Check(object)) { - if (encode->utf8) - return encode_string(object); - else - return encode_string(object); + if (encode->utf8) + return encode_string(object); + else + return encode_string(object); } else if (PyUnicode_Check(object)) { return encode_unicode(object); } else if (PyFloat_Check(object)) {