Q66: What is a memoryview object and how does it achieve Zero-Copy I/O?
memoryview exposes Python's internal Buffer Protocol. It permits slicing binary array data (like bytes or bytearray) without copying bytes in memory, delivering $O(1)$ zero-copy buffer slicing for network and file I/O operations.
Zero-Copy Memoryview Slicing
data = bytearray(b"X" * 10_000_000) # 10 MB buffer
mv = memoryview(data)
slice_mv = mv[1000:2000] # O(1) Zero-copy slice window💡 memoryview creates a view slice without duplicating 10MB of buffer memory.
Key Takeaways
- Exposes internal Buffer Protocol.
- Enables zero-copy slicing of large byte arrays.
Knowledge Check
What is the time and space complexity of slicing a 1GB bytearray using memoryview?