From 0436e5bd863282e459026d385120ae8e29616e1a Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 12 Apr 2026 19:55:30 -1000 Subject: [PATCH] [core] Optimize main loop with -O2 Add __attribute__((optimize("O2"))) to the main loop functions (loop_task on ESP32, codegen loop() on other platforms) so GCC inlines scheduler helpers and loop bookkeeping more aggressively. Under -Os, GCC outlines small functions (Scheduler::call helpers, millis conversions, etc.) that are called every loop iteration. With -O2, these get inlined into the loop body, reducing call overhead on the hottest code path in the firmware. ESP32: loop_task grows from 303 to 416 bytes (+113 bytes). ESP8266: no change (already fully inlined via ESPHOME_ALWAYS_INLINE). --- esphome/components/esp32/core.cpp | 2 +- esphome/writer.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/esphome/components/esp32/core.cpp b/esphome/components/esp32/core.cpp index add50dcf4da..1fa51f1d9e6 100644 --- a/esphome/components/esp32/core.cpp +++ b/esphome/components/esp32/core.cpp @@ -65,7 +65,7 @@ static StaticTask_t loop_task_tcb; // NOLINT(cppcoreguidelines-avoid-non- static StackType_t loop_task_stack[ESPHOME_LOOP_TASK_STACK_SIZE]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) -void loop_task(void *pv_params) { +void __attribute__((optimize("O2"))) loop_task(void *pv_params) { setup(); while (true) { App.loop(); diff --git a/esphome/writer.py b/esphome/writer.py index 06a22301184..c2e0d08fa4f 100644 --- a/esphome/writer.py +++ b/esphome/writer.py @@ -45,7 +45,7 @@ void setup() { App.setup(); } -void loop() { +void __attribute__((optimize("O2"))) loop() { App.loop(); } """,