ArduinoJSON: Memory Allocation

ArduinoHardwareSoftware & Coding

You can declare two types of JSON Documents with the ArduinoJson library - StaticJsonDocument and DynamicJsonDocument. Both need the capacity (in bytes) to be specified at the time of declaration.

For static docs, the declaration syntax is −

StaticJsonDocument<capacity> doc_name;

For example −

StaticJsonDocument<256> myDoc;

For dynamic docs, the declaration syntax is −

DynamicJsonDocument doc_name(capacity);

For example,

DynamicJsonDocument myDoc(4096);

The difference between the two is that static doc allocates memory on the stack. Therefore, it doesn't need to call malloc() and free(), and is therefore faster.

Dynamic docs allocate memory in the heap, and therefore, is slightly slower and should be used for larger JSONs, which don't fit in the stack memory.

The thumb rule is to use static docs for JSONs smaller than 1 kB, and dynamic docs above 1 kB.

You can read more about StaticJsonDocument here.

And, more about DynamicJsonDocument here.

You can also read about how to determine the capacity of your JsonDocument here.

raja
Published on 26-Jul-2021 10:17:17
Advertisements