Sorting Strings in Rust: Why Allocating Lowercase Strings Beats Lazy Comparison
Matching Puzzle Pieces and Disappointing Benchmarks
A Rust developer benchmarks three ways to case-insensitively sort strings: pre-computing lowercase with `sort_by_cached_key`, lazily converting during comparison with `sort_by` and `flat_map`, and using the `unicase` crate. Tests on an M2 Max show that despite extra allocations, `sort_by_cached_key` wins for lists of 5 or more, while `unicase` surprisingly outperforms both for larger inputs, revealing that lazy conversion overhead outweighs allocation costs.
The real surprise is that Unicase can often be faster, despite making the comparison more complex.