From 33b548e2476dde409443ef4e6c10b41f1434fc14 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 13 Oct 2020 08:34:46 -0500 Subject: [PATCH] Reduce ORM overhead when the old state was already written to the database (#41736) We can avoid processing the relationship when the old state was already written to the database which will common case with a commit interval of 1s. Since we already know the value for old_state_id we can use it instead of asking sqlalchemy to process the relationship at flush/commit time which can significantly speed up sqlalchemy's _emit_insert_statements implementation. --- homeassistant/components/recorder/__init__.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index 4c74e5e8d41..18d364315b7 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -404,7 +404,11 @@ class Recorder(threading.Thread): dbstate = States.from_event(event) has_new_state = event.data.get("new_state") if dbstate.entity_id in self._old_states: - dbstate.old_state = self._old_states.pop(dbstate.entity_id) + old_state = self._old_states.pop(dbstate.entity_id) + if old_state.state_id: + dbstate.old_state_id = old_state.state_id + else: + dbstate.old_state = old_state if not has_new_state: dbstate.state = None dbstate.event = dbevent