theelims / ESP32-sveltekit

A simple and extensible framework for ESP32 based IoT projects with a feature-rich, beautiful, and responsive front-end build with Sveltekit, Tailwind CSS and DaisyUI. This is a project template to get you started in no time with a fully integrated build chain.
https://theelims.github.io/ESP32-sveltekit/
Other
90 stars 15 forks source link

heap fragmentation #39

Open SolarDaniel opened 2 months ago

SolarDaniel commented 2 months ago

In some services Strings are used as members. They are initialized with empty buffer. As an example WifiSettingsService.h.

// Struct defining the wifi settings in WifiSettingsService.h
typedef struct
{
    String ssid;
    String password;
    bool staticIPConfig;
    IPAddress localIP;
    IPAddress gatewayIP;
    IPAddress subnetMask;
    IPAddress dnsIP1;
    IPAddress dnsIP2;
    bool available;
} wifi_settings_t;

When changing the settings from the GUI, a JSON document is dynamically allocated and the update() is called, where the Strings are set. The String class then allocates memory and copies the content to the memory from the heap, where it lives until it's changed again. But the JSON document (sometimes 2000 to 4000 bytes) is freed after the update. A gap is left on the heap. It will be used later on, but the heap gets fragmented and the maximum allocatable heap shrinks.

The same happens when using persistancy, when initial data is loaded from FS..

My proposal is to use String.reserve() in the constructor for these members. The size of the content is known in advance and can be well limited. So the framework would leave the maximum heap possible to the user and not fragment the heap already at startup.