JsonDocument::garbageCollect()
Description
JsonDocument::garbageCollect()
reclaims the memory leaked when removing and replacing values.
The monotonic allocator inside JsonDocument
can efficiently allocate memory but is unable to release memory. As a consequence, when you remove a value from a JsonDocument
, the memory allocated to this value remains in the memory pool. Similarly, when you replace a value, the memory attached to this value (such as a string) remains in the pool.
When you repeatedly remove or replace values in a JsonDocument
, you create a memory leak that will inevitably fill the memory pool until it’s full. The function JsonDocument::garbageCollect()
helps you mitigate this problem by allowing you to reclaim the leaked memory.
Internally, this function makes a complete copy of the JsonDocument
, so it’s very slow and temporarily requires a lot of memory.
Every reference (JsonArray
, JsonObject
, or JsonVariant
) acquired before calling garbageCollect()
is invalidated.
Unlike shrinkToFit()
, this function doesn’t reduce the capacity of the memory pool.
This function was added in ArduinoJson 6.15.0
Signature
void garbageCollect() const;
Example
doc["msg"] = String("Hello, world!");
doc["msg"] = String("How are you!"); // original string is still in memory
Serial.println(doc.memoryUsage()); // 35
doc.garbageCollect();
Serial.println(doc.memoryUsage()); // 21