From 58498bacff0960648c3a7556623a07e38d84540d Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 22 Mar 2026 16:21:25 -1000 Subject: [PATCH] [binary_sensor] Skip old_state construction when no full_state_callbacks registered --- esphome/core/entity_base.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/esphome/core/entity_base.h b/esphome/core/entity_base.h index 60132a4c18..b6785a9aab 100644 --- a/esphome/core/entity_base.h +++ b/esphome/core/entity_base.h @@ -351,9 +351,12 @@ template class StatefulEntityBase : public EntityBase { } else if (!had_state) { return false; // already invalidated, no change } - // State changed — capture old state, then update storage before firing callbacks - // so callback code can inspect the entity's current state via get_state()/has_state() - optional old_state = had_state ? optional(this->get_state()) : nullopt; + // State changed — update storage before firing callbacks so callback code + // can inspect the entity's current state via get_state()/has_state() + // Only construct old_state optional when full_state_callbacks need it + optional old_state; + if (!this->full_state_callbacks_.empty()) + old_state = had_state ? optional(this->get_state()) : nullopt; this->flags_.has_state = new_state.has_value(); if (new_state.has_value()) { this->set_state_value_(new_state.value());