`cdef` vs. `cpdef`: The Performance Divide
`cdef` functions are purely C-level, offering maximum speed and callable only from Cython, while `cpdef` functions generate both fast C and Python-callable versions, balancing speed with Python interoperability.
The top 3
- cdef: The Pure C Velocity Unlocked: `cdef` functions compile directly to C, completely bypassing the Python interpreter and its overhead. This offers the absolute fastest execution, making them ideal for performance-critical internal computations not exposed to Python, often achieving significant speedups over Python functions.
- cpdef: Bridging Python & C, Costing Less: `cpdef` functions generate both a C-level function and a Python wrapper, allowing calls from both Cython/C and pure Python. While providing C-speed when called from Cython, they incur a minor, measurable overhead compared to `cdef` due to the wrapper's Python interoperability.
- The Performance Fork: When to Choose Which: Choose `cdef` for internal, performance-critical routines that do not need to be called from Python, maximizing speed. Opt for `cpdef` when functions require both high performance and direct accessibility from pure Python code, accepting its minimal wrapper overhead for flexibility.
Sources
Open the full topic