Skip to content

Rust Preprocessor Performance Analysis

Why is the Rust parser slower than expected?

The initial estimate was ~20,000 lines/ms based on pure Rust performance, but actual measurements show ~4,000-5,000 lines/ms. Here's why:

1. PyO3 FFI Overhead (75-80% performance loss)

The biggest factor is the Python-Rust Foreign Function Interface (FFI) overhead:

  • String conversion: Every call converts Python strings to Rust strings (UTF-8 validation) and back
  • GIL management: Acquiring and releasing Python's Global Interpreter Lock
  • PyResult wrapping: Error handling across the language boundary
  • Object allocation: Creating Python objects for return values

2. Actual Performance Measurements

Implementation Throughput Relative Speed
Pure Rust (theoretical) ~20,000 lines/ms 28.5x
Rust with PyO3 (actual) ~4,500 lines/ms 6.4x
Python optimized ~700 lines/ms 1.0x
Python simple ~2,000 lines/ms 2.8x
Python original AST ~35 lines/ms 0.05x

3. Performance Breakdown

For a 1,000 line file: - Pure Rust processing: ~0.05ms (theoretical) - PyO3 overhead: ~0.15ms (string conversion, GIL, etc.) - Total Rust time: ~0.20ms - Python optimized: ~1.4ms

4. Why it's still worth it

Despite the FFI overhead, the Rust implementation provides:

  1. 2.4x speedup over simple Python implementation
  2. 6.4x speedup over the optimized Python regex approach (when comparing actual measurements)
  3. Consistent performance across different file sizes
  4. Better scalability for very large files
  5. Lower memory usage (no intermediate Python objects)

5. Optimization Opportunities

To get closer to the theoretical performance:

  1. Batch processing: Process multiple files in one call to amortize FFI overhead
  2. Zero-copy strings: Use PyString views instead of converting to Rust String
  3. Unsafe optimizations: Skip some UTF-8 validation for trusted input
  4. Native module: Ship as part of a larger Rust module to avoid repeated FFI calls

6. Conclusion

The performance "drop" from 20,000 to 4,500 lines/ms is entirely due to Python-Rust interop overhead, not the Rust implementation itself. This is a common pattern with PyO3 extensions:

  • Small operations: FFI overhead dominates (75-80% overhead)
  • Large operations: Rust performance shines through
  • Sweet spot: Operations taking >1ms benefit most from Rust

For netherframe's use case, even with the FFI overhead, the Rust preprocessor is fast enough to make preprocessing essentially "free" - processing even large 10,000 line modules in just 2ms.