Skip to content

Commit

Permalink
Add a fast path for URL construction when the netloc is the host (#1271)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Oct 15, 2024
1 parent ca9f47a commit 598cc0c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
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

0 comments on commit 598cc0c

Please sign in to comment.