From 76ebb0df0852214be410123956186c02032bca30 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 25 Aug 2024 20:49:31 -1000 Subject: [PATCH] Improve performance of generate diffs of state change events (#124601) dict comps are inlined in cpython 3.12+ --- homeassistant/components/websocket_api/messages.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/websocket_api/messages.py b/homeassistant/components/websocket_api/messages.py index 238f8be0c3b..0a8200c5700 100644 --- a/homeassistant/components/websocket_api/messages.py +++ b/homeassistant/components/websocket_api/messages.py @@ -224,9 +224,12 @@ def _state_diff_event( if (old_attributes := old_state.attributes) != ( new_attributes := new_state.attributes ): - for key, value in new_attributes.items(): - if old_attributes.get(key) != value: - additions.setdefault(COMPRESSED_STATE_ATTRIBUTES, {})[key] = value + if added := { + key: value + for key, value in new_attributes.items() + if key not in old_attributes or old_attributes[key] != value + }: + additions[COMPRESSED_STATE_ATTRIBUTES] = added if removed := old_attributes.keys() - new_attributes: # sets are not JSON serializable by default so we convert to list # here if there are any values to avoid jumping into the json_encoder_default