Title: gh-150878: Speed up json.dumps(ensure_ascii=False) for long strings by gaborbernat · Pull Request #150879 · python/cpython · GitHub
Open Graph Title: gh-150878: Speed up json.dumps(ensure_ascii=False) for long strings by gaborbernat · Pull Request #150879 · python/cpython
X Title: gh-150878: Speed up json.dumps(ensure_ascii=False) for long strings by gaborbernat · Pull Request #150879 · python/cpython
Description: When json.dumps runs with ensure_ascii=False, it sizes each escaped string one character at a time in escape_size, after which write_escaped_unicode copies the string verbatim when nothing needs escaping. In this mode a character needs escaping only when c == '"', c == '\\', or c < 0x20; non-ASCII is kept verbatim. For a long string with no such character, common for text values including Western-European (Latin-1) text, that per-character sizing scan is pure overhead before the verbatim copy. This detects the no-escape case on the one-byte (Latin-1) representation eight bytes at a time, returning the verbatim size after about one eighth of the work. It is the ensure_ascii=False counterpart to #150876; with the decode-side scan in #150872 the three changes cover JSON string scanning end to end, on three different code paths. What we do now (scalar, one code point at a time) for (i = 0, output_size = 2; i < input_chars; i++) { Py_UCS4 c = PyUnicode_READ(kind, input, i); switch (c) { case '\\': case '"': case '\b': case '\f': case '\n': case '\r': case '\t': output_size += 2; break; default: output_size += (c <= 0x1f) ? 6 : 1; // non-ASCII (>= 0x20) kept verbatim } } A byte needs escaping when c == '"' || c == '\\' || c < 0x20. For a long string with none of those, this reads and tests every byte just to learn the output is the input plus two quotes. What SWAR does (8 bytes at a time, in one register) SWAR is "SIMD within a register": load 8 bytes into a single uint64_t and test all 8 lanes at once with ordinary integer ops. for (; j + 8 <= input_chars; j += 8) { memcpy(&w, p + j, 8); mq = haszero(w ^ (0x22 * 0x0101010101010101)); // any lane == '"' ? ms = haszero(w ^ (0x5c * 0x0101010101010101)); // any lane == '\\' ? mlo = haszero(w & 0xE0E0E0E0E0E0E0E0); // any lane < 0x20 ? if (mq | ms | mlo) { needs_escape = 1; break; } // escape needed -> scalar } if (!needs_escape) return input_chars + 2; // no escape anywhere haszero(v) = (v - 0x0101…) & ~v & 0x8080… lights the high bit of exactly the zero lanes, with no false positives or negatives. Broadcasting a byte (b * 0x0101…) and XOR-ing turns "equals b" into "is zero"; < 0x20 is "top three bits all zero", detected as haszero(w & 0xE0…). A Latin-1 byte (>= 0x80) is not in this set, so long runs of European text skip eight at a time too. At the first lane that needs escaping the loop breaks and the existing per-character loop computes the exact size and does the work. A length guard keeps short strings (the common dict key) on the original loop, where the fast path's setup would not pay off. These are the same 0x0101… / 0x8080… masks that Objects/unicodeobject.c and Objects/stringlib/find_max_char.h already use for ASCII scanning. When and how this changes performance json.dumps(..., ensure_ascii=False), current encoder versus this change: Document shape Effect One long text field (~16 KB string) 5.8x faster Long Western-European (Latin-1) text values 4.2x faster Many 200-character ASCII string values 3.9x faster Realistic mixed records (short and medium strings) 1.4x faster Short keys, strings that need escaping no change Strings with characters above U+00FF no change (scalar path) This change is confined to ensure_ascii=False, the non-default mode, so it reaches fewer callers than the default-path change in #150876; within that mode the win matches. Correctness Output is byte-identical to the current encoder. Verified against the full test_json suite and a 199-case differential corpus that places each escape-relevant character (", \\, control chars, and characters above U+007F) at every offset across the eight-byte window, in both ensure_ascii=True and ensure_ascii=False modes. Every output matched. Benchmark import json, pyperf d = lambda o: json.dumps(o, ensure_ascii=False) objs = { "long_ascii": [("x"*200) for _ in range(200)], "long_latin1": [("café résumé naïve "*15) for _ in range(200)], "text_blob": {"body": "lorem ipsum dolor "*900}, "short_keys": {f"k{i}": i for i in range(2000)}, "nonascii": ["中文 текст 😀 "*30 for _ in range(200)], "mixed_real": [{"id":i,"name":f"user_{i}","bio":"hello world "*10} for i in range(300)], } runner = pyperf.Runner() for n, o in objs.items(): runner.bench_func(f"dumpsF/{n}", lambda o=o: d(o)) References for the bit tricks: Sean Anderson, Bit Twiddling Hacks (zero byte, byte equal to n); Henry S. Warren Jr., Hacker's Delight, 2nd ed., chapter 6. It is not the SIMD parsing backend from #142915: it adds no intrinsics, no CPU detection, and no build configuration, and it does not depend on #125022. Resolves #150878. Issue: gh-150878
Open Graph Description: When json.dumps runs with ensure_ascii=False, it sizes each escaped string one character at a time in escape_size, after which write_escaped_unicode copies the string verbatim when nothing needs es...
X Description: When json.dumps runs with ensure_ascii=False, it sizes each escaped string one character at a time in escape_size, after which write_escaped_unicode copies the string verbatim when nothing needs es...
Opengraph URL: https://github.com/python/cpython/pull/150879
X: @github
Domain: github.com
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:103c878f-8ee7-cad6-3c51-44197373b237 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | 9820:1FAE:F7D6E6:14C91A5:6B020EAA |
| html-safe-nonce | 68c4a5aed1d1a6a6cc80ad33bb5d8eae17be560e72147905ee43eec4d57535f2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5ODIwOjFGQUU6RjdENkU2OjE0QzkxQTU6NkIwMjBFQUEiLCJ2aXNpdG9yX2lkIjoiNzc1OTk4NjA5MTQ1MjY2NTUxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 98c6fc243b863b9bd16060e0db74f95901139c0482940951beb6a9cd5cabb1bc |
| hovercard-subject-tag | pull_request:3797826458 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/python/cpython/pull/150879/files |
| twitter:image | https://avatars.githubusercontent.com/u/690238?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/690238?s=400&v=4 |
| og:image:alt | When json.dumps runs with ensure_ascii=False, it sizes each escaped string one character at a time in escape_size, after which write_escaped_unicode copies the string verbatim when nothing needs es... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width