What are the differences between StaticJsonBuffer
and DynamicJsonBuffer
?
StaticJsonBuffer |
DynamicJsonBuffer |
|
---|---|---|
Size | fixed | variable |
Location | stack (1) | heap |
Memory overhead | small | big |
Code size | small | big |
Speed | fast | slow(3) |
Cleanup | automatic | automatic |
Reusable | no(2) | no(2) |
(1) on most platforms, the stack cannot occupy all the RAM; for instance, it’s limited to 4KB on the ESP8266.
(2) there is a workaround (see How to reuse a JsonBuffer
? if you are looking for troubles).
(3) A DynamicJsonBuffer
calls malloc()
to allocate its memory, and it may have to do this several times if it needs to grow. However, you can specify an initial size to the constructor, so as to make sure that the buffer is big enough and that no further allocation will be needed.
As a general rule, if your StaticJsonBuffer
is bigger than 2KB, then it may be a good time to switch to a DynamicJsonBuffer
.
Where to go next?
The ArduinoJson ebook describes StaticJsonBuffer
and DynamicJsonBuffer
in detail and gives guidelines for choosing between one or the other.
It begin with two complete tutorials, one on deserialization, the other on serialization. The last chapter shows the best practices in several sample projects.
The book also explains the difference between “stack,” “heap” and “global” memories. These concepts are often overlooked by programmers coming from other languages, but it is the most common source of failure with ArduinoJson.