From 08d6a3d9d47422a06e2528fb164e1ca3119fce9a Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 22 Mar 2022 21:21:56 -1000 Subject: [PATCH] Cache newly written state attribute ids (#68355) --- homeassistant/components/recorder/__init__.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index aae6576c225..d046fe30d5c 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -1116,9 +1116,18 @@ class Recorder(threading.Thread): if dbstate in self.event_session: self.event_session.expunge(dbstate) self._pending_expunge = [] - self._pending_state_attributes = {} self.event_session.commit() + # We just committed the state attributes to the database + # and we now know the attributes_ids. We can save + # a many selects for matching attributes by loading them + # into the LRU cache now. + for state_attr in self._pending_state_attributes.values(): + self._state_attributes_ids[ + state_attr.shared_attrs + ] = state_attr.attributes_id + self._pending_state_attributes = {} + # Expire is an expensive operation (frequently more expensive # than the flush and commit itself) so we only # do it after EXPIRE_AFTER_COMMITS commits