When should I use memoryview in Python2.7? I just can't find any profit of using it over regular bytearray. Also memoryview doesn't support string methods, that is making it absolutely unusable. Am I wrong?
Python Memoryview vs Bytearray?
Asked Answered
Ok, finally, working on the network software, I found a use case for memoryview
s: when we have a fixed size socket buffer and we want to perform fast slicing on it (read/write data from any given position w/o creating extra copies in memory), something like this:
buf = bytearray(4096)
mview = memoryview(buf)
socket.recv_into(mview)
print mview[256:]
So, in some cases it's handy to have a memoryview on a bytearray.
The only thing you should keep in mind with such scheme: after you created a memoryview on a bytearray, you can't change the size of a bytearray, until you delete this memoryview, bytearray will be limited to its initial size and throw BufferError: Existing exports of data: object cannot be re-sized
error on every attempt to add more data there.
© 2022 - 2024 — McMap. All rights reserved.