René's URL Explorer Experiment


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

direct link

Domain: github.com

react-profiling0
react-import-mapreact,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-controllerpull_requests
route-actionfiles
fetch-noncev2:103c878f-8ee7-cad6-3c51-44197373b237
current-catalog-service-hashae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b
request-id9820:1FAE:F7D6E6:14C91A5:6B020EAA
html-safe-nonce68c4a5aed1d1a6a6cc80ad33bb5d8eae17be560e72147905ee43eec4d57535f2
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5ODIwOjFGQUU6RjdENkU2OjE0QzkxQTU6NkIwMjBFQUEiLCJ2aXNpdG9yX2lkIjoiNzc1OTk4NjA5MTQ1MjY2NTUxNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac98c6fc243b863b9bd16060e0db74f95901139c0482940951beb6a9cd5cabb1bc
hovercard-subject-tagpull_request:3797826458
github-keyboard-shortcutsrepository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///pull_requests/show/files
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/python/cpython/pull/150879/files
twitter:imagehttps://avatars.githubusercontent.com/u/690238?s=400&v=4
twitter:cardsummary_large_image
og:imagehttps://avatars.githubusercontent.com/u/690238?s=400&v=4
og:image:altWhen 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_nameGitHub
og:typeobject
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
diff-viewunified
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive full-width
disable-turbotrue
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/pull/150879/files#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F150879%2Ffiles
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fpull%2F150879%2Ffiles
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fpull_requests%2Fshow%2Ffiles&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/pull/150879/files
Reloadhttps://github.com/python/cpython/pull/150879/files
Reloadhttps://github.com/python/cpython/pull/150879/files
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
Sign up for GitHub https://github.com/signup?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
terms of servicehttps://docs.github.com/terms
privacy statementhttps://docs.github.com/privacy
Sign inhttps://github.com/login?return_to=%2Fpython%2Fcpython%2Fissues%2Fnew%2Fchoose
gaborbernathttps://github.com/gaborbernat
python:mainhttps://github.com/python/cpython/tree/main
gaborbernat:opt/json-swar-escape-sizehttps://github.com/gaborbernat/cpython/tree/opt/json-swar-escape-size
Conversation 27 https://github.com/python/cpython/pull/150879
Commits 5 https://github.com/python/cpython/pull/150879/commits
Checks 51 https://github.com/python/cpython/pull/150879/checks
Files changed 3 https://github.com/python/cpython/pull/150879/files
gh-150878: Speed up json.dumps(ensure_ascii=False) for long strings https://github.com/python/cpython/pull/150879/files#top
Show all changes 5 commits https://github.com/python/cpython/pull/150879/files
0d5d951 gh-150878: Speed up json.dumps(ensure_ascii=False) for long strings gaborbernat Jun 3, 2026 https://github.com/python/cpython/pull/150879/commits/0d5d951251ec89a40cbb409341a303f8a68f8daf
27a63b9 Add tests exercising the ensure_ascii=False encoder paths gaborbernat Jun 3, 2026 https://github.com/python/cpython/pull/150879/commits/27a63b9fe9b18355c40455da4ac28364f98dd746
466e2d7 ♻️ refactor(_json): clarify SWAR path, guard one word gaborbernat Jun 9, 2026 https://github.com/python/cpython/pull/150879/commits/466e2d7f14f0de2b0c534974c7fa45a6fc214041
e62a2b3 📝 json: address review on ensure_ascii=False speedup gaborbernat Jun 10, 2026 https://github.com/python/cpython/pull/150879/commits/e62a2b39d01442f5315002a1f52a2c00f70a0d11
223a0db Update _json.c gaborbernat Jun 11, 2026 https://github.com/python/cpython/pull/150879/commits/223a0db1593e69f1cff623aae0c0292cfee696fe
Clear filters https://github.com/python/cpython/pull/150879/files
Please reload this pagehttps://github.com/python/cpython/pull/150879/files
Please reload this pagehttps://github.com/python/cpython/pull/150879/files
test_unicode.py https://github.com/python/cpython/pull/150879/files#diff-7be4773d4cc7317c354b9ab4aaa2d533d0f45de1b90c757f6fa5539b29a0deb2
2026-06-03-11-49-35.gh-issue-150878.ZCL1T0.rst https://github.com/python/cpython/pull/150879/files#diff-68aa16e8031d11c1f802a4744993d84554281fa2142e7b7be5ba6979d65d2974
_json.c https://github.com/python/cpython/pull/150879/files#diff-efe183ae0b85e5b8d9bbbc588452dd4de80b39fd5c5174ee499ba554217a39ed
Lib/test/test_json/test_unicode.pyhttps://github.com/python/cpython/pull/150879/files#diff-7be4773d4cc7317c354b9ab4aaa2d533d0f45de1b90c757f6fa5539b29a0deb2
View file https://github.com/gaborbernat/cpython/blob/223a0db1593e69f1cff623aae0c0292cfee696fe/Lib/test/test_json/test_unicode.py
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/150879/{{ revealButtonHref }}
https://github.com/python/cpython/pull/150879/files#diff-7be4773d4cc7317c354b9ab4aaa2d533d0f45de1b90c757f6fa5539b29a0deb2
Misc/NEWS.d/next/Library/2026-06-03-11-49-35.gh-issue-150878.ZCL1T0.rsthttps://github.com/python/cpython/pull/150879/files#diff-68aa16e8031d11c1f802a4744993d84554281fa2142e7b7be5ba6979d65d2974
View file https://github.com/gaborbernat/cpython/blob/223a0db1593e69f1cff623aae0c0292cfee696fe/Misc/NEWS.d/next/Library/2026-06-03-11-49-35.gh-issue-150878.ZCL1T0.rst
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/150879/{{ revealButtonHref }}
Modules/_json.chttps://github.com/python/cpython/pull/150879/files#diff-efe183ae0b85e5b8d9bbbc588452dd4de80b39fd5c5174ee499ba554217a39ed
View file https://github.com/gaborbernat/cpython/blob/223a0db1593e69f1cff623aae0c0292cfee696fe/Modules/_json.c
Open in desktop https://desktop.github.com
https://github.co/hiddenchars
https://github.com/python/cpython/pull/150879/{{ revealButtonHref }}
https://github.com/python/cpython/pull/150879/files#diff-efe183ae0b85e5b8d9bbbc588452dd4de80b39fd5c5174ee499ba554217a39ed
Please reload this pagehttps://github.com/python/cpython/pull/150879/files
https://github.com/python/cpython/pull/150879/files#diff-efe183ae0b85e5b8d9bbbc588452dd4de80b39fd5c5174ee499ba554217a39ed
Please reload this pagehttps://github.com/python/cpython/pull/150879/files
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.