Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a fast path for URL construction when the netloc is the host #1271

Merged
merged 7 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/1271.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of constructing :class:`~yarl.URL` when the net location is only the host -- by :user:`bdraco`.
26 changes: 19 additions & 7 deletions yarl/_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,14 +284,20 @@ def __new__(
else:
host = ""
host = cls._encode_host(host, validate_host=False)
raw_user = cls._REQUOTER(username) if username else username
raw_password = cls._REQUOTER(password) if password else password
netloc = cls._make_netloc(raw_user, raw_password, host, port)
# Remove brackets as host encoder adds back brackets for IPv6 addresses
cache["raw_host"] = host[1:-1] if "[" in host else host
cache["raw_user"] = raw_user
cache["raw_password"] = raw_password
cache["explicit_port"] = port
if port is None and password is None and username is None:
# Fast path for URLs without user, password and port
netloc = host
cache["raw_user"] = None
cache["raw_password"] = None
else:
raw_user = cls._REQUOTER(username) if username else username
raw_password = cls._REQUOTER(password) if password else password
netloc = cls._make_netloc(raw_user, raw_password, host, port)
cache["raw_user"] = raw_user
cache["raw_password"] = raw_password

if path:
path = cls._PATH_REQUOTER(path)
Expand Down Expand Up @@ -368,7 +374,10 @@ def build(
elif host:
if port is not None:
port = None if port == DEFAULT_PORTS.get(scheme) else port
netloc = cls._make_netloc(user, password, host, port)
if port is None and user is None and password is None:
netloc = host
else:
netloc = cls._make_netloc(user, password, host, port)
else:
netloc = ""
else: # not encoded
Expand All @@ -384,7 +393,10 @@ def build(
if _host is not None:
if port is not None:
port = None if port == DEFAULT_PORTS.get(scheme) else port
netloc = cls._make_netloc(user, password, _host, port, True)
if port is None and user is None and password is None:
netloc = _host
else:
netloc = cls._make_netloc(user, password, _host, port, True)

path = cls._PATH_QUOTER(path) if path else path
if path and netloc:
Expand Down