From ae80d8073973b719eaf78a9a4667e97fdb393d6a Mon Sep 17 00:00:00 2001 From: Kurt Griffiths Date: Thu, 22 Sep 2016 15:04:35 -0600 Subject: [PATCH] perf(uri): Replace if...else with try...except in the decode function (#905) Most of the time the token will be found in the dict, so let's optimize for that and avoid an extra membership check (if token in _HEX_TO_BYTE). --- falcon/util/uri.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/falcon/util/uri.py b/falcon/util/uri.py index 959b2c9..7b16de9 100644 --- a/falcon/util/uri.py +++ b/falcon/util/uri.py @@ -164,7 +164,7 @@ Returns: """ -if six.PY2: +if six.PY2: # NOQA: C901 - Work around a bug in flake8 McCabe scoring # This map construction is based on urllib _HEX_TO_BYTE = dict((a + b, (chr(int(a + b, 16)), int(a + b, 16))) @@ -213,10 +213,11 @@ if six.PY2: decoded_uri = tokens[0] for token in tokens[1:]: token_partial = token[:2] - if token_partial in _HEX_TO_BYTE: + try: char, byte = _HEX_TO_BYTE[token_partial] - else: + except KeyError: char, byte = '%', 0 + decoded_uri += char + (token[2:] if byte else token) only_ascii = only_ascii and (byte <= 127) @@ -271,9 +272,9 @@ else: decoded_uri = tokens[0] for token in tokens[1:]: token_partial = token[:2] - if token_partial in _HEX_TO_BYTE: + try: decoded_uri += _HEX_TO_BYTE[token_partial] + token[2:] - else: + except KeyError: # malformed percentage like "x=%" or "y=%+" decoded_uri += b'%' + token