From 10e7e15088527023c052dffb02e4e186dafa9e42 Mon Sep 17 00:00:00 2001 From: Tim Abbott Date: Fri, 14 Feb 2020 10:20:54 -0800 Subject: [PATCH] user_agent: Compile the regular expression. We use this single regular expression for processing essentially every request, so it's definitely worth hinting to Python that we're going to do so by compiling it. Saves about 40us per request. --- zerver/lib/user_agent.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/zerver/lib/user_agent.py b/zerver/lib/user_agent.py index 5aa5156b6f..2f2496a3d5 100644 --- a/zerver/lib/user_agent.py +++ b/zerver/lib/user_agent.py @@ -4,11 +4,13 @@ from typing import Dict # Warning: If you change this parsing, please test using # zerver/tests/test_decorators.py # And extend zerver/tests/fixtures/user_agents_unique with any new test cases +pattern = re.compile( + """^ (?P [^/ ]* [^0-9/(]* ) + (/ (?P [^/ ]* ))? + ([ /] .*)? + $""", re.X) + def parse_user_agent(user_agent: str) -> Dict[str, str]: - match = re.match( - """^ (?P [^/ ]* [^0-9/(]* ) - (/ (?P [^/ ]* ))? - ([ /] .*)? - $""", user_agent, re.X) + match = pattern.match(user_agent) assert match is not None return match.groupdict()