High-Throughput Buffering with memoryview
Slicing standard Python `bytes` (`data[10:]`) allocates a brand new memory copy. Wrapping buffers in `memoryview(buf)` allows zero-copy slicing and in-place mutation, eliminating gigabytes of temporary allocations in network pipelines 🏎️.
buf = bytearray(b"FAST_CAR")
view = memoryview(buf)
# Mutate through view without copying:
view[5:8] = b"BUS"
print(f"Underlying buffer: {buf.decode()} 🏎️")
print(f"Slice view: {bytes(view[:4]).decode()}")
# 13. High-Throughput Buffering with memoryview Slicing standard Python `bytes` (`data[10:]`) allocates a brand new memory copy. Wrapping buffers in `memoryview(buf)` allows zero-copy slicing and in-place mutation, eliminating gigabytes of temporary allocations in network pipelines 🏎️. ```python buf = bytearray(b"FAST_CAR") view = memoryview(buf) # Mutate through view without copying: view[5:8] = b"BUS" print(f"Underlying buffer: {buf.decode()} 🏎️") print(f"Slice view: {bytes(view[:4]).decode()}") ``` In network loops, passing `view[offset:]` into `sock.send()` allows you to advance through unsent portions of a buffer during partial writes without creating a single heap object 🚀! --- ### Question What major performance advantage does `memoryview` offer over slicing immutable `bytes`? 🧠 - [ ] a. It provides zero-copy pointer views into existing memory buffers, avoiding expensive memory copies and GC overhead 🏎️ - [ ] b. It increases CPU instruction cache size automatically - [ ] c. It allows string methods to run on binary data - [ ] d. It encrypts buffer slices against memory inspection attacks --- ### Challenge Create `buf = bytearray(b'FAST_CAR')`. Wrap with `memoryview(buf)`, replace slice `[5:8]` with `b'BUS'`, and print `buf.decode()`. 🎯 <details> <summary>Solution</summary> ```python buf = bytearray(b'FAST_CAR') mv = memoryview(buf) mv[5:8] = b'BUS' print(buf.decode()) ``` </details>