#๐Ÿ”’ Does my code benefit from memoryview?

7 messages ยท Page 1 of 1 (latest)

mystic quiver
#

hello, i have a class that provides methods for reading data types from a buffer. i do not want to create many copies of the data because it would be inefficient. In my mind, using memoryview would be good for this problem.

Here is an example implementation:

class Reader:
    def __init__(self, buffer: bytes | bytearray, byteorder: str = "little") -> None:
        self.view = memoryview(buffer)
        self.byteorder = byteorder

    def read_byte(self, offset: int) -> int:
        return self.view[offset]

    def read_sized_int(self, offset: int, size: int) -> int:
        view = self.view[offset : offset + size]
        return int.from_bytes(view, byteorder=self.byteorder)

Does casting buffer as a memoryview object provide any tangible benefit? How would I be able to tell? pithink

slender plumeBOT
#

@mystic quiver

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

half blade
#

it avoids memory copying

#

but you should probably benchmark to find out if it matters

mystic quiver
#

thank you

slender plumeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.