From c9d7d842ff3e40af699a87f946bfbbbca4e52c58 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Mon, 15 Jun 2026 15:18:28 +0200 Subject: [PATCH] Avoid walking script variable ChainMap twice when tracing (#173665) --- homeassistant/helpers/trace.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/homeassistant/helpers/trace.py b/homeassistant/helpers/trace.py index b3ddcd1b37b0..f0d9c8cab6b5 100644 --- a/homeassistant/helpers/trace.py +++ b/homeassistant/helpers/trace.py @@ -87,13 +87,15 @@ class TraceElement: if variables is None: variables = {} last_variables = self._last_variables - variables_cv.set(dict(variables)) - changed_variables = { + # variables is often a ChainMap which is costly to iterate, so flatten + # it once and reuse the snapshot for both the baseline and the diff. + snapshot = dict(variables) + variables_cv.set(snapshot) + self._variables = { key: value - for key, value in variables.items() + for key, value in snapshot.items() if key not in last_variables or last_variables[key] != value } - self._variables = changed_variables def as_dict(self) -> dict[str, Any]: """Return dictionary version of this TraceElement."""