From ec3475910f20bd07f0a32113bdbea06612f8e5b8 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 28 Jan 2023 17:05:06 -1000 Subject: [PATCH] Improve websocket throughput of state changes (#86855) After the start event we tend to get an event storm of state changes which can get the websocket behind. #86854 will help with that a bit, but we can reduce the overhead to build a state diff when the attributes have not changed --- homeassistant/components/websocket_api/messages.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/websocket_api/messages.py b/homeassistant/components/websocket_api/messages.py index 5c01484f912..15965b37faa 100644 --- a/homeassistant/components/websocket_api/messages.py +++ b/homeassistant/components/websocket_api/messages.py @@ -161,12 +161,14 @@ def _state_diff( additions[COMPRESSED_STATE_CONTEXT]["id"] = new_state.context.id else: additions[COMPRESSED_STATE_CONTEXT] = new_state.context.id - old_attributes = old_state.attributes - for key, value in new_state.attributes.items(): - if old_attributes.get(key) != value: - additions.setdefault(COMPRESSED_STATE_ATTRIBUTES, {})[key] = value - if removed := set(old_attributes).difference(new_state.attributes): - diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: removed} + 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 removed := set(old_attributes).difference(new_attributes): + diff[STATE_DIFF_REMOVALS] = {COMPRESSED_STATE_ATTRIBUTES: removed} return {ENTITY_EVENT_CHANGE: {new_state.entity_id: diff}}