peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
549 stars 116 forks source link

Don't allocate another bytes object in as_read #98

Closed waveform80 closed 1 year ago

waveform80 commented 1 year ago

The current as_read implementation causes the allocation of an arbitrary length bytes object (msg) which is then copied into the pre-allocated bytearray (data) via a memoryview (buffer).

However, given we already have a convenient memoryview of the bytearray available we can avoid this allocation and simply read the data directly into the pre-allocated buffer using sock.readinto. This results in a potentially substantial memory saving (depending on the length of message being received) and reduces fragmentation.

peterhinch commented 1 year ago

Thank you for that, a very worthwhile improvement.

So why I didn't write it that way? I guess sock.readino didn't exist when I started out on ESP8266.

waveform80 commented 1 year ago

I figured that was very likely the case :)