From 125ca8672e928b19a62c2e4b761fb29fe2a34ae3 Mon Sep 17 00:00:00 2001 From: Parker Loflin Date: Mon, 16 Nov 2026 00:05:19 +0000 Subject: [PATCH] util: Avoid allocating when sorting paths by extension (#67019) ## Summary With `"sort_order": "extension"`, `compare_rel_paths_by` compared extensions with `to_lowercase()`, which allocates two `String`s for each pair of file names it compares. `compare_lowercase` compares ASCII strings by their lowercased bytes and falls back to `to_lowercase()` otherwise. For ASCII, `to_lowercase()` only lowercases each byte, so the order is unchanged. The project panel sorts its visible entries with this comparator, on a background thread, each time it rebuilds them. `cargo bench -p project_panel --bench sorting`, which sorts 96k entries from a Linux checkout, in extension order: | Sort mode | Before | After | |---|---|---| | `DirectoriesFirst` | 39.7 ms | 14.7 ms | | `Mixed` | 38.6 ms | 12.4 ms | | `FilesFirst` | 35.4 ms | 11.6 ms | The other sort orders don't run this code. They measured 1 to 3% faster, as did Unicode order, which this change can't affect, so that difference is noise. ## Testing - `cargo test -p util --lib paths` passes. - `cargo test -p project_panel` passes. - `./script/clippy -p util` passes. - Outside Zed, `compare_lowercase` matched `a.to_lowercase().cmp(&b.to_lowercase())` on 6 million random pairs of ASCII and non-ASCII strings, and on every pair of the 252 extensions in the benchmark snapshot. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - N/A --- crates/util/src/paths.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rs index 9719e4d1212..493ba563d59 100644 --- a/crates/util/src/paths.rs +++ b/crates/util/src/paths.rs @@ -1103,6 +1103,16 @@ fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering { } } +fn compare_lowercase(a: &str, b: &str) -> Ordering { + if a.is_ascii() && b.is_ascii() { + a.bytes() + .map(|byte| byte.to_ascii_lowercase()) + .cmp(b.bytes().map(|byte| byte.to_ascii_lowercase())) + } else { + a.to_lowercase().cmp(&b.to_lowercase()) + } +} + fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) { if filename.is_empty() { return (None, None); @@ -1249,10 +1259,8 @@ pub fn compare_rel_paths_by( if order == SortOrder::Extension { // Directories have no extension and must take part in this comparison too, // otherwise mixed mode would produce an inconsistent (non-transitive) ordering. - let extension_ordering = a_ext - .unwrap_or_default() - .to_lowercase() - .cmp(&b_ext.unwrap_or_default().to_lowercase()); + let extension_ordering = + compare_lowercase(a_ext.unwrap_or_default(), b_ext.unwrap_or_default()); if !extension_ordering.is_eq() { return extension_ordering; }