From 8dbbd0ded057479f5cb3171a30f5c0858348bcaf Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 18 Sep 2022 04:48:04 -0500 Subject: [PATCH] Cache template regex compiles (#78529) --- homeassistant/helpers/template.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 3999231eb68..5a4d631a8c8 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1719,7 +1719,13 @@ def regex_match(value, find="", ignorecase=False): if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 - return bool(re.match(find, value, flags)) + return bool(_regex_cache(find, flags).match(value)) + + +@lru_cache(maxsize=128) +def _regex_cache(find: str, flags: int) -> re.Pattern: + """Cache compiled regex.""" + return re.compile(find, flags) def regex_replace(value="", find="", replace="", ignorecase=False): @@ -1727,8 +1733,7 @@ def regex_replace(value="", find="", replace="", ignorecase=False): if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 - regex = re.compile(find, flags) - return regex.sub(replace, value) + return _regex_cache(find, flags).sub(replace, value) def regex_search(value, find="", ignorecase=False): @@ -1736,7 +1741,7 @@ def regex_search(value, find="", ignorecase=False): if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 - return bool(re.search(find, value, flags)) + return bool(_regex_cache(find, flags).search(value)) def regex_findall_index(value, find="", index=0, ignorecase=False): @@ -1749,7 +1754,7 @@ def regex_findall(value, find="", ignorecase=False): if not isinstance(value, str): value = str(value) flags = re.I if ignorecase else 0 - return re.findall(find, value, flags) + return _regex_cache(find, flags).findall(value) def bitwise_and(first_value, second_value):