Improve performance of as_compressed_state (#141800)

We have to build all of these at startup.

Its a lot faster to compare floats instead
of datetime objects. Since we already have to
fetch last_changed_timestamp, use it to compare
with last_updated_timestamp since we already know
we will have last_updated_timestamp
This commit is contained in:
J. Nick Koston 2025-03-30 10:20:24 -10:00 committed by GitHub
parent 5bfe034b4d
commit 0d511c697c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1935,13 +1935,14 @@ class State:
# to avoid callers outside of this module
# from misusing it by mistake.
context = state_context._as_dict # noqa: SLF001
last_changed_timestamp = self.last_changed_timestamp
compressed_state: CompressedState = {
COMPRESSED_STATE_STATE: self.state,
COMPRESSED_STATE_ATTRIBUTES: self.attributes,
COMPRESSED_STATE_CONTEXT: context,
COMPRESSED_STATE_LAST_CHANGED: self.last_changed_timestamp,
COMPRESSED_STATE_LAST_CHANGED: last_changed_timestamp,
}
if self.last_changed != self.last_updated:
if last_changed_timestamp != self.last_updated_timestamp:
compressed_state[COMPRESSED_STATE_LAST_UPDATED] = (
self.last_updated_timestamp
)