Skip to content

gh-163115: Speed up urllib.parse.quote() and quote_plus() for ASCII str inputs - #163116

Open
gatewaytofredom wants to merge 3 commits into
python:mainfrom
gatewaytofredom:perf/urllib-quote-ascii-fastpath
Open

gatewaytofredom wants to merge 3 commits into
python:mainfrom
gatewaytofredom:perf/urllib-quote-ascii-fastpath

Conversation

@gatewaytofredom

@gatewaytofredom gatewaytofredom commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Bypass the bytes encoding and per-byte map(quoter, bs) loop in quote() and quote_plus() for exact ASCII str inputs (str.rstrip() when all-safe, str.translate() otherwise). Default translation tables are initialized lazily to avoid import overhead, and all caches are cleared by clear_cache().

Note: the three lazy module-level tables (_STR_QUOTER_*) avoid lru_cache lookup overhead on the default safe paths (~6–15% faster on short mixed strings). We can drop them though and route everything through _str_quoter_table() if you prefer a smaller diff.

Benchmarks (timeit.repeat, min of 7, x86_64 Linux):

Benchmark script
python
import timeit
from urllib.parse import quote, quote_plus, urlencode

PATH_MIXED = "/api/v1/users/alice smith/profile?tab=settings"
PATH_SAFE = "abcdefghijklmnopqrstuvwxyz0123456789/foo/bar"
FORM = {
    "name": "Alice Smith",
    "email": "alice@example.com",
    "redirect": "/dashboard/home?tab=1",
    "lang": "en-US",
    "token": "abc123XYZ_.-~",
    "notes": "hello world & more!",
}

cases = [
    ("quote(mixed ASCII path)", 50_000, lambda: quote(PATH_MIXED)),
    ("quote(all-safe ASCII path)", 50_000, lambda: quote(PATH_SAFE)),
    ('quote_plus("hello world foo@bar.com")', 50_000, lambda: quote_plus("hello world foo@bar.com")),
    ('quote_plus("abcdef123456")', 50_000, lambda: quote_plus("abcdef123456")),
    ("urlencode(6-field dict)", 20_000, lambda: urlencode(FORM)),
    ('quote("café /résumé")', 50_000, lambda: quote("café /résumé")),
    ('quote("日本語テスト/パス" * 5)', 20_000, lambda: quote("日本語テスト/パス" * 5)),
    ('quote_plus("café résumé")', 50_000, lambda: quote_plus("café résumé")),
    ('quote_plus("café_résumé")', 50_000, lambda: quote_plus("café_résumé")),
    ('quote(b"/api/v1/alice smith")', 50_000, lambda: quote(b"/api/v1/alice smith")),
    ('quote_plus(b"hello world")', 50_000, lambda: quote_plus(b"hello world")),
]

for name, n, fn in cases:
    fn()  # warmup
    t = min(timeit.repeat(fn, number=n, repeat=7)) * 1000
    print(f"{name:<40} {t:7.2f} ms")
Case main PR Speedup
quote(mixed ASCII path) 84.02 ms 44.59 ms 1.88x
quote(all-safe ASCII path) 21.77 ms 17.38 ms 1.25x
quote_plus("hello world foo@bar.com") 64.84 ms 26.92 ms 2.41x
quote_plus("abcdef123456") 18.41 ms 9.28 ms 1.98x
urlencode(6-field dict) 157.19 ms 93.35 ms 1.68x
quote("café /résumé") 45.50 ms 46.44 ms 0.98x
quote("日本語テスト/パス" * 5) 70.30 ms 70.39 ms 1.00x
quote_plus("café résumé") 56.21 ms 57.66 ms 0.97x
quote_plus("café_résumé") 48.46 ms 46.69 ms 1.04x
quote(b"/api/v1/alice smith") 52.91 ms 53.99 ms 0.98x
quote_plus(b"hello world") 35.56 ms 35.97 ms 0.99x
import urllib.parse (self, median of 15) 0.709 ms 0.763 ms +0.055 ms

…SCII str inputs

Bypass the bytes encoding and map(quoter, bs) loop for exact ASCII str
inputs using str.rstrip() and str.translate(). Initialize default
translation tables lazily, cache custom safe tables via lru_cache, and
clear all of them in clear_cache().
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Dec 3, 2026
@picnixz
picnixz enabled auto-merge (squash) December 3, 2026 22:54
@picnixz
picnixz disabled auto-merge December 3, 2026 22:54
@picnixz

picnixz commented Dec 3, 2026

Copy link
Copy Markdown
Member

Misclick. I wanted to say that I believe this complicates the code for something that is usually not the hot path in application. I do not think this is worth it. If users are worried about performance, a 3rd party package written in C is better but this is not the stdlib role here IMO.

@picnixz picnixz closed this Dec 3, 2026
@picnixz

picnixz commented Dec 3, 2026

Copy link
Copy Markdown
Member

Plesse remove the cache stuff so that I can estimate the actual diff.

@picnixz

picnixz commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

But unlike the unquote optimization this one seems much more complex.

@picnixz picnixz reopened this Dec 3, 2026
@gatewaytofredom

Copy link
Copy Markdown
Contributor Author

Removed the globals (STR_QUOTER*) and special-case branches. Mixed ASCII quote() is still 1.60x–1.73x faster and quote_plus() is 1.50x–2.12x faster on my machine.

Comment thread Lib/urllib/parse.py Outdated
if (type(string) is str and string.isascii() and type(safe) is str and
(encoding is None or
(type(encoding) is str and encoding in _ASCII_ENCODINGS)) and
(errors is None or isinstance(errors, str))):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this check is useless IMO

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll remove that, i was concerned about a bizarre custom class

Comment thread Lib/urllib/parse.py Outdated
Comment on lines +1104 to +1105
(encoding is None or
(type(encoding) is str and encoding in _ASCII_ENCODINGS)) and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this one as well, why checking for encoding being a string? it looks really odd, wa it an LLM suggestion? if so why?

Comment thread Lib/urllib/parse.py Outdated
if isinstance(string, str):
if not string:
return string
if (type(string) is str and string.isascii() and type(safe) is str and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think isinstance checks arr just better

Comment thread Lib/urllib/parse.py Outdated
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It also does not have safe default to '/'.
"""
if (type(string) is str and string and string.isascii() and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this huge check is the sane, why not having a function making the check?

@bedevere-app

bedevere-app Bot commented Dec 3, 2026

Copy link
Copy Markdown

A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated.

Once you have made the requested changes, please leave a comment on this pull request containing the phrase I have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

Comment thread Lib/urllib/parse.py

def _quote_ascii(string, safe, encoding, plus=False):
if (isinstance(string, str) and string.isascii() and
isinstance(safe, str) and encoding in _ASCII_ENCODINGS):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see that the encoding needs to be ascii. Problem is that encoding can be lowercased, or without dashes. I now wonder whether we really need this as this makes the check more complex.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can drop _ASCII_ENCODINGS and just check if encoding is None to cover the default path for quote()/quote_plus()/urlencode(). It would still offer speedups

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting changes type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants