A memoryview exposes a homogeneous memory buffer without copying it. It supports indexing, slicing, and memory sharing, making it useful when copying large arrays would consume time or memory. section 4.1.1
Use memoryviews when the bottleneck involves array data movement or Python-level access:
- In Cython, convert NumPy arrays into typed memoryviews so inner loops communicate with raw array representations instead of repeatedly using Python machinery. section 5.4.1 section 5.6.1
- Treat the optimization as part of a profiling loop: memoryviews can remove substantial overhead, but remaining Python interactions may still limit performance. section 5.4.1 section 5.8
- Prefer views when shared data is intended; copies allocate new raw data, while views recreate only view metadata and generally use less memory. section 4.1.1
Typed memoryviews in a Game of Life kernel
A Cython kernel can declare parameters such as cnp.uint8_t[:,:] world and cnp.uint8_t[:,:] extended_world. The function then copies the board into a preallocated extended buffer, including wrapped boundaries, before processing cells without repeated Python-level array access. This trades extra memory for simpler boundary handling and potentially faster computation. section 5.6.1
