Avoiding malloc when interfacing with json and asyncio sockets #15527
mzakharocsc
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
Re asyncio see #7868 - in particular the response of @dpgeorge. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
When faced with low-memory constrained systems, and sending large json payloads over async MQTT sockets, it is essential to avoid malloc of large buffers along the transmit path. Unfortunately, micropython currently does not provide malloc-free API to accomplish such goals.
First problem is converting a python datastructure to json bytes and reusing an existing buffer. One could accomplish such goal with the following API:
Unfortunately,
buf.truncate(0)
API does not exist in micropython, nor willbuf.getvalue()
be malloc-free.Proposal 1: add
.truncate(val)
API to io.BytesIO class in micropython, to allow resetting the buffer to 0 every time it is usedProposal 2: create a variant of
buf.getvalue(None)
with optional parameter that will be a micropython extension to return payload without additional malloc - pointer to the data.Finally, sending the payload over the socket is hamstrung by asyncio
write()
anddrain()
API. asynciowrite()
function builds an internalself.out_buf
buffer which also calls malloc.Proposal 3: add a asyncio
write_and_drain()
API to write to socket in one go and avoid extra malloc.We have implemented local versions of the 3 proposals in our attempt to build a json-async-mqtt-socket interface that reuses a single buffer for communicating large payloads. It allowed us to successfully target systems with very low available memory, which was not possible before. Question is whether proposed changes would be useful to the community at large.
Beta Was this translation helpful? Give feedback.
All reactions