From de831b6e87397552400ba8c6c78b4c985840fb98 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 23 Mar 2024 18:24:52 -1000 Subject: [PATCH] Small performance improvement to template expand (#114086) * Small performance improvement to template expand - Avoid fetching entity sources each loop - Skip already found entities - Avoid startswith in favor of equality check * unneeded changes --- homeassistant/helpers/template.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index bb0d868bf3c..58a7e27714c 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -1252,6 +1252,7 @@ def expand(hass: HomeAssistant, *args: Any) -> Iterable[State]: search = list(args) found = {} + sources = entity_helper.entity_sources(hass) while search: entity = search.pop() if isinstance(entity, str): @@ -1267,14 +1268,17 @@ def expand(hass: HomeAssistant, *args: Any) -> Iterable[State]: # ignore other types continue - if entity_id.startswith(_GROUP_DOMAIN_PREFIX) or ( - (source := entity_helper.entity_sources(hass).get(entity_id)) - and source["domain"] == "group" + if entity_id in found: + continue + + domain = entity.domain + if domain == "group" or ( + (source := sources.get(entity_id)) and source["domain"] == "group" ): # Collect state will be called in here since it's wrapped if group_entities := entity.attributes.get(ATTR_ENTITY_ID): search += group_entities - elif entity_id.startswith(_ZONE_DOMAIN_PREFIX): + elif domain == "zone": if zone_entities := entity.attributes.get(ATTR_PERSONS): search += zone_entities else: