Reduce Switch component memory usage by 8 bytes per instance (#9112)

This commit is contained in:
J. Nick Koston 2025-06-17 20:14:03 +02:00 committed by GitHub
parent 7ed095e635
commit 47e7988c8e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -21,7 +21,7 @@ const int RESTORE_MODE_PERSISTENT_MASK = 0x02;
const int RESTORE_MODE_INVERTED_MASK = 0x04; const int RESTORE_MODE_INVERTED_MASK = 0x04;
const int RESTORE_MODE_DISABLED_MASK = 0x08; const int RESTORE_MODE_DISABLED_MASK = 0x08;
enum SwitchRestoreMode { enum SwitchRestoreMode : uint8_t {
SWITCH_ALWAYS_OFF = !RESTORE_MODE_ON_MASK, SWITCH_ALWAYS_OFF = !RESTORE_MODE_ON_MASK,
SWITCH_ALWAYS_ON = RESTORE_MODE_ON_MASK, SWITCH_ALWAYS_ON = RESTORE_MODE_ON_MASK,
SWITCH_RESTORE_DEFAULT_OFF = RESTORE_MODE_PERSISTENT_MASK, SWITCH_RESTORE_DEFAULT_OFF = RESTORE_MODE_PERSISTENT_MASK,
@ -49,12 +49,12 @@ class Switch : public EntityBase, public EntityBase_DeviceClass {
*/ */
void publish_state(bool state); void publish_state(bool state);
/// The current reported state of the binary sensor.
bool state;
/// Indicates whether or not state is to be retrieved from flash and how /// Indicates whether or not state is to be retrieved from flash and how
SwitchRestoreMode restore_mode{SWITCH_RESTORE_DEFAULT_OFF}; SwitchRestoreMode restore_mode{SWITCH_RESTORE_DEFAULT_OFF};
/// The current reported state of the binary sensor.
bool state;
/** Turn this switch on. This is called by the front-end. /** Turn this switch on. This is called by the front-end.
* *
* For implementing switches, please override write_state. * For implementing switches, please override write_state.
@ -123,10 +123,16 @@ class Switch : public EntityBase, public EntityBase_DeviceClass {
*/ */
virtual void write_state(bool state) = 0; virtual void write_state(bool state) = 0;
CallbackManager<void(bool)> state_callback_{}; // Pointer first (4 bytes)
bool inverted_{false};
Deduplicator<bool> publish_dedup_;
ESPPreferenceObject rtc_; ESPPreferenceObject rtc_;
// CallbackManager (12 bytes on 32-bit - contains vector)
CallbackManager<void(bool)> state_callback_{};
// Small types grouped together
Deduplicator<bool> publish_dedup_; // 2 bytes (bool has_value_ + bool last_value_)
bool inverted_{false}; // 1 byte
// Total: 3 bytes, 1 byte padding
}; };
#define LOG_SWITCH(prefix, type, obj) log_switch((TAG), (prefix), LOG_STR_LITERAL(type), (obj)) #define LOG_SWITCH(prefix, type, obj) log_switch((TAG), (prefix), LOG_STR_LITERAL(type), (obj))