From 50edc334dec634ef788ce72aca33b1454a32a3d7 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 7 Jan 2024 17:36:03 -1000 Subject: [PATCH] Refactor sensor recorder _get_sensor_states to check for state class first (#107046) The state class check is cheap and the entity filter check is much more expensive, so do the state class check first --- homeassistant/components/sensor/recorder.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/sensor/recorder.py b/homeassistant/components/sensor/recorder.py index d08a20636ab..1aba934aba4 100644 --- a/homeassistant/components/sensor/recorder.py +++ b/homeassistant/components/sensor/recorder.py @@ -68,13 +68,19 @@ LINK_DEV_STATISTICS = "https://my.home-assistant.io/redirect/developer_statistic def _get_sensor_states(hass: HomeAssistant) -> list[State]: """Get the current state of all sensors for which to compile statistics.""" - all_sensors = hass.states.all(DOMAIN) instance = get_instance(hass) + # We check for state class first before calling the filter + # function as the filter function is much more expensive + # than checking the state class return [ state - for state in all_sensors - if instance.entity_filter(state.entity_id) - and try_parse_enum(SensorStateClass, state.attributes.get(ATTR_STATE_CLASS)) + for state in hass.states.all(DOMAIN) + if (state_class := state.attributes.get(ATTR_STATE_CLASS)) + and ( + type(state_class) is SensorStateClass + or try_parse_enum(SensorStateClass, state_class) + ) + and instance.entity_filter(state.entity_id) ]