From ac97097167ccf91e5fb810862c977b704d55ec1c Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 12 Feb 2023 13:13:13 -0600 Subject: [PATCH] Speed up template lru_caches (#87942) By avoiding the argument unpacking these functions are faster and reduce stack overhead --- homeassistant/helpers/template.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index fd0fa920309..b1e1dc067c6 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -966,9 +966,9 @@ def _collect_state(hass: HomeAssistant, entity_id: str) -> None: entity_collect.entities.add(entity_id) -@lru_cache(maxsize=CACHED_TEMPLATE_STATES) -def _template_state_no_collect(hass: HomeAssistant, state: State) -> TemplateState: - return TemplateState(hass, state, collect=False) +_template_state_no_collect = lru_cache(maxsize=CACHED_TEMPLATE_STATES)( + partial(TemplateState, collect=False) +) def _state_generator( @@ -990,9 +990,7 @@ def _get_state(hass: HomeAssistant, entity_id: str) -> TemplateState | None: return _get_template_state_from_state(hass, entity_id, hass.states.get(entity_id)) -@lru_cache(maxsize=CACHED_TEMPLATE_STATES) -def _template_state(hass: HomeAssistant, state: State) -> TemplateState: - return TemplateState(hass, state) +_template_state = lru_cache(maxsize=CACHED_TEMPLATE_STATES)(TemplateState) def _get_template_state_from_state( @@ -1812,10 +1810,7 @@ def regex_match(value, find="", ignorecase=False): 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) +_regex_cache = lru_cache(maxsize=128)(re.compile) def regex_replace(value="", find="", replace="", ignorecase=False):