Zero-Copy Data Transfer for NumPy & STL Containers
Pybind11 optimizes data exchange, especially for large datasets, by supporting zero-copy interoperability with NumPy arrays and providing mechanisms like 'opaque types' and `pybind11/stl_bind.h` to expose C++ STL containers as native Python objects, avoiding expensive copy operations.
The top 3
- Zero-Copy vs. Copying: Up to 100x Speed Advantage: Zero-copy data transfer can yield significant performance improvements, with benchmarks showing up to 10-100 times faster execution for large NumPy arrays and C++ vectors compared to traditional copying, by eliminating memory allocation and data duplication overhead.
- Pybind11's Zero-Copy Core: Buffer Protocol & Contiguous Memory: Pybind11 achieves zero-copy by leveraging Python's buffer protocol for NumPy arrays and the inherent contiguous memory layout of C++ STL containers like `std::vector`. This allows C++ code to directly access and manipulate the underlying memory of Python objects without creating new copies.
- Top 3 Data Structures for Pybind11 Zero-Copy: The most effective data structures for zero-copy data transfer with Pybind11 are `numpy.ndarray` on the Python side and `std::vector` (for 1D data) or custom C++ classes exposing a contiguous memory buffer on the C++ side. `std::string_view` also supports zero-copy for string data.
Sources
Open the full topic