[preferences] Compile out loop() when flash_write_interval is non-zero

The write_interval == 0 case (sync every loop) is only used on host
or for testing. For the vast majority of real devices using the default
60s interval, loop() and the runtime branch are unnecessary overhead.

Use a compile-time define to separate the two modes so that:
- Normal case: no loop() override, no write_interval_ member, just set_interval
- Zero interval case: loop() syncs every iteration, no interval needed
This commit is contained in:
J. Nick Koston
2026-03-18 16:08:24 -10:00
parent 403ba262c6
commit 0594e22e3a
3 changed files with 13 additions and 11 deletions
+5 -1
View File
@@ -21,5 +21,9 @@ CONFIG_SCHEMA = cv.Schema(
@coroutine_with_priority(CoroPriority.PREFERENCES)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
cg.add(var.set_write_interval(config[CONF_FLASH_WRITE_INTERVAL]))
write_interval = config[CONF_FLASH_WRITE_INTERVAL]
if write_interval == 0:
cg.add_define("USE_PREFERENCES_SYNC_EVERY_LOOP")
else:
cg.add(var.set_write_interval(write_interval))
await cg.register_component(var, config)
+7 -10
View File
@@ -8,24 +8,21 @@ namespace preferences {
class IntervalSyncer final : public Component {
public:
#ifdef USE_PREFERENCES_SYNC_EVERY_LOOP
void loop() override { global_preferences->sync(); }
#else
void set_write_interval(uint32_t write_interval) { this->write_interval_ = write_interval; }
void setup() override {
if (this->write_interval_ != 0) {
set_interval(this->write_interval_, []() { global_preferences->sync(); });
// When using interval-based syncing, we don't need the loop
this->disable_loop();
}
}
void loop() override {
if (this->write_interval_ == 0) {
global_preferences->sync();
}
this->set_interval(this->write_interval_, []() { global_preferences->sync(); });
}
#endif
void on_shutdown() override { global_preferences->sync(); }
float get_setup_priority() const override { return setup_priority::BUS; }
#ifndef USE_PREFERENCES_SYNC_EVERY_LOOP
protected:
uint32_t write_interval_{60000};
#endif
};
} // namespace preferences
+1
View File
@@ -117,6 +117,7 @@
#define USE_NUMBER
#define USE_OUTPUT
#define USE_POWER_SUPPLY
#define USE_PREFERENCES_SYNC_EVERY_LOOP
#define USE_QR_CODE
#define USE_SAFE_MODE_CALLBACK
#define USE_SELECT