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.
This commit is contained in:
J. Nick Koston 2020-10-13 08:34:46 -05:00 committed by GitHub
parent 52c93edb53
commit 33b548e247
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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