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.
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.