BasicJsonDocument<T>::shrinkToFit()
Description
BasicJsonDocument<T>::shrinkToFit()
reduces the capacity of the memory pool to match the current usage. Use this function to release some memory.
There is no reverse operation to resize the memory pool; you can only shrink it.
Unlike JsonDocument::garbageCollect()
, this function doesn’t reclaim leaked memory blocks.
This function was added in ArduinoJson 6.14.0
Example
Here is how you can deserialize using as a lot of memory, and then release what’s unused.
DynamicJsonDocument doc(8192);
deserializeJson(doc, json);
doc.shrinkToFit();
On ESP8266, you can call ESP.getMaxFreeBlockSize()
to know how much memory you can use:
DynamicJsonDocument doc(ESP.getMaxFreeBlockSize() - 512);
deserializeJson(doc, json);
doc.shrinkToFit();
Similarly, on ESP32, you can call ESP.getMaxAllocHeap()
:
DynamicJsonDocument doc(ESP.getMaxAllocHeap() - 1024);
deserializeJson(doc, json);
doc.shrinkToFit();
These two functions return the size of the largest block of free memory.
The result may be significantly lower than the total available memory (ESP.getFreeHeap()
) if the heap is fragmented.
See also
JsonDocument::garbageCollect()
- The “Advanced Techniques” chapter of Mastering ArduinoJson uses
shrinkToFit()
in the “Automatic capacity” section.