diff --git a/homeassistant/helpers/trace.py b/homeassistant/helpers/trace.py index b3ddcd1b37b..f0d9c8cab6b 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."""