Heap on Embedded Devices: Analysis and Improvement
blog.cesanta.com
blog.cesanta.com
Embedded engineering 101: statically allocate everything, and try not to push the stack too much. But you can not do this with JS :(
Yep. malloc() is generally discouraged on those things and should be seen as a big red flag in any code review.
Many embedded systems allocate just once at startup and these "really dumb" implementations are completely sufficient. The vendors provide a fast, low-overhead solution by default and trust that developers can go find a more appropriate allocator if they need it for their application. Luckily we have many implementations to choose from!
The tool can be found at https://github.com/cesanta/smart.js/tree/master/tools/heaplo...
If anybody knows other similar open source tooling, please share!
Standard allocators that I'm familiar with use minimum 8 bytes overhead per allocation. Umm_malloc uses 4 bytes overhead: twice less. If we have 200 allocations, it's 800 wasted bytes already.
Plus, it uses "best-fit" algorithm, so that the resulting fragmentation is far less than with the "first-fit", which is used in standard allocators. (if one really wants to, she can use "first-fit" on umm_malloc, too)
The exception is in state machines where you know, in a deterministic way, what the memory layout should be at every given state, and then you can use heaps to get memory overlap between code pieces that operate exclusively of each other.
I'm just looking forward to getting my hands on the ESP32. Espressif is packing a lot of bang for you buck into those; I just hope they get around to making a native SDK that is better documented. I've used the native SDK on the ESP8266 a bit and it was miserable.
We could replace them with whatever, but umm_malloc is still the most efficient allocator for memory-constrained devices that I'm aware of.
For the truly paranoid, the compiler must be re-written so that bits within the stack words must remain unutilized and the remaining bits include a cryptographically-signed bit field. E.g. a 32-bit machine can allocate 8 bits of each word for application data and 24 bits for authentication.