Normally, slicing a bytes or bytearray object copies the sliced portion into a brand-new object. memoryview instead wraps the original buffer and exposes the same slicing/indexing interface without copying any data — slicing a memoryview returns another memoryview pointing into the same underlying memory. This matters for performance when working with large binary data, like parsing a big network buffer or file, where copying would be wasteful.
1Understanding Memoryview
Normally, slicing a bytes or bytearray object copies the sliced portion into a brand-new object. memoryview instead wraps the original buffer and exposes the same slicing/indexing interface without copying any data — slicing a memoryview returns another memoryview pointing into the same underlying memory. This matters for performance when working with large binary data, like parsing a big network buffer or file, where copying would be wasteful.
Reach for memoryview specifically when profiling shows that slicing large bytes/bytearray objects is copying more data than necessary — for small, everyday byte strings, it's not worth the added complexity.
data = bytearray(b"Hello, World!")
view = memoryview(data)
print(view[7:12].tobytes())2Practical Example
Here is a real-world application of Memoryview showing how it is used in production Python code.
buf = bytearray(b"abcdef")
view = memoryview(buf)
view[0:2] = b"XY"
print(buf)3Best Practices
Follow these guidelines when working with Memoryview:
1. Use memoryview when repeatedly slicing large binary buffers to avoid the cost of copying data on every slice
2. Combine memoryview with bytearray, not bytes, when you also need to modify the underlying buffer in place
3. Call bytes(mv) or bytearray(mv) to materialize a real copy once you're done working with the zero-copy view
Tip: Reach for memoryview specifically when profiling shows that slicing large bytes/bytearray objects is copying more data than necessary — for small, everyday byte strings, it's not worth the added complexity.
data = bytearray(b"Hello, World!")
view = memoryview(data)
print(view[7:12].tobytes())