Memory Views: Zero-Copy for NumPy & Python Arrays in `nogil`
Cython's typed memory views offer direct, zero-copy access to the underlying data buffers of Python objects like NumPy arrays or Python's `array` module, making them ideal for high-performance operations within `nogil` blocks. This allows C-speed manipulation of data without the GIL, though memory views themselves do not support the full NumPy API and re-binding them in `nogil` can be costly due to GIL re-acquisition.
The top 3
- Buffer Protocol: Memory Views' Zero-Copy Core: Cython memory views achieve zero-copy data access by directly leveraging Python's PEP 3118 buffer protocol, allowing C-speed manipulation of raw data buffers from objects like NumPy arrays and `array.array` without Python object overhead.
- Memory Views: Up to 300x Speedup in `nogil`: Cython memory views, especially within `nogil` blocks, deliver substantial performance gains for numerical tasks. Benchmarks have shown speedups up to 300 times faster for slicing large buffers compared to pure Python, often matching the performance of raw C pointers.
- Memory Views vs. `np.ndarray` Typing: Generality & GIL Bypass: Cython memory views offer superior generality compared to `np.ndarray` typing by working with any object supporting Python's buffer interface. Their key advantage is enabling true parallelism in `nogil` blocks, as they allow slicing and direct memory access without re-acquiring the Global Interpreter Lock, which `np.ndarray` typing cannot do.
Sources
Open the full topic