From f7300e433adbc3b134d9c5c20489802714e03a76 Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Fri, 31 May 2024 09:10:56 -0400 Subject: [PATCH 1/2] Tiny optimization --- src/klein/_resource.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/klein/_resource.py b/src/klein/_resource.py index f0e2148f..8b78adcd 100644 --- a/src/klein/_resource.py +++ b/src/klein/_resource.py @@ -91,12 +91,11 @@ def extractURLparts(request: IRequest) -> Tuple[str, str, int, str, str]: server_port = request.getHost().port else: server_port = 0 - if (bool(request.isSecure()), server_port) not in [ + is_secure = bool(request.isSecure()) + if (is_secure, server_port) not in [ (True, 443), (False, 80), - (False, 0), - (True, 0), - ]: + ] or server_port == 0: server_name = b"%s:%d" % (server_name, server_port) script_name = b"" @@ -113,7 +112,7 @@ def extractURLparts(request: IRequest) -> Tuple[str, str, int, str, str]: if not path_info.startswith(b"/"): path_info = b"/" + path_info - url_scheme = "https" if request.isSecure() else "http" + url_scheme = "https" if is_secure else "http" utf8Failures = [] try: From 671dd1f96c94dd9f544e45838adef675a1b8526c Mon Sep 17 00:00:00 2001 From: Itamar Turner-Trauring Date: Tue, 17 Sep 2024 12:25:34 -0400 Subject: [PATCH 2/2] Another maybe OK optimization. --- src/klein/_resource.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/klein/_resource.py b/src/klein/_resource.py index d10b25db..4107357b 100644 --- a/src/klein/_resource.py +++ b/src/klein/_resource.py @@ -231,6 +231,12 @@ def process(r: object) -> Any: returns an IRenderable, then render it and let the result of that bubble back up. """ + # isinstance() is faster than providedBy(), so this speeds up the + # very common case of returning pre-rendered results, at the cost + # of slightly slowing down other cases. + if isinstance(r, (bytes, str)): + return r + if isinstance(r, Response): r = r._applyToRequest(request)