From cd5b19ab0d8aac48a0e0dce8361305eba33102ed Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 22 Mar 2026 18:38:34 -1000 Subject: [PATCH] [binary_sensor] Fast-path dedup in send_state_internal before virtual dispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Check state == new_state directly before calling virtual set_new_state. Avoids the virtual dispatch chain (BinarySensor::set_new_state → StatefulEntityBase::set_new_state → virtual get_state()) on the common no-change path. Fixes -20% CodSpeed regression on BinarySensorPublish_NoChange benchmark. --- esphome/components/binary_sensor/binary_sensor.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/esphome/components/binary_sensor/binary_sensor.h b/esphome/components/binary_sensor/binary_sensor.h index 9525832705..28c156763a 100644 --- a/esphome/components/binary_sensor/binary_sensor.h +++ b/esphome/components/binary_sensor/binary_sensor.h @@ -57,7 +57,12 @@ class BinarySensor : public StatefulEntityBase { // ========== INTERNAL METHODS ========== // (In most use cases you won't need these) - void send_state_internal(bool new_state) { this->set_new_state(new_state); } + void send_state_internal(bool new_state) { + // Fast path: skip virtual dispatch when state hasn't changed + if (this->flags_.has_state && this->state == new_state) + return; + this->set_new_state(new_state); + } /// Return whether this binary sensor has outputted a state. virtual bool is_status_binary_sensor() const;