Visual Studio Code, rebuilt in Rust
Rust
perf(settings): compile wordify and group regexes once
rokartur57fa470b385d
diff --git a/native/crates/app/src/settings_editor.rs b/native/crates/app/src/settings_editor.rsindex 08d5a03758e..ec91ef37033 100644--- a/native/crates/app/src/settings_editor.rs+++ b/native/crates/app/src/settings_editor.rs@@ -9,8 +9,10 @@ pub mod lists;pub mod validation;use std::cmp::Ordering;-use std::collections::HashSet;+use std::cell::RefCell;+use std::collections::{HashMap, HashSet};use std::path::Path;+use std::sync::LazyLock;use config::configuration::{Configuration, Inspected, Overrides};use config::model::ConfigurationModel;@@ -587,22 +589,35 @@ const KNOWN_TERM_MAPPINGS: &[(&str, &str)] = &[("resharper", "ReSharper"),];+struct WordifyPatterns {+ dots: regex::Regex,+ camel: regex::Regex,+ capitals: regex::Regex,+ words: regex::Regex,+ terms: Vec<(regex::Regex, &'static str)>,+}++// Compiled once: the tree wordifies every visible row's key each frame, and compiling these took 90% of a scroll frame.+static WORDIFY_PATTERNS: LazyLock<WordifyPatterns> = LazyLock::new(|| WordifyPatterns {+ dots: regex::Regex::new(r"\.([a-z0-9])").expect("valid"),+ camel: regex::Regex::new(r"([a-z0-9])([A-Z])").expect("valid"),+ capitals: regex::Regex::new(r"([A-Z]+)([A-Z][a-z])").expect("valid"),+ words: regex::Regex::new(r"\b\w+\b").expect("valid"),+ terms: KNOWN_TERM_MAPPINGS.iter().map(|(term, replacement)| (regex::RegexBuilder::new(&format!(r"\b{term}\b")).case_insensitive(true).build().expect("valid"), *replacement)).collect(),+});+/// `wordifyKey`.pub fn wordify_key(key: &str) -> String {- let dots = regex::Regex::new(r"\.([a-z0-9])").expect("valid");- let key = dots.replace_all(key, |captures: ®ex::Captures| format!(" \u{203A} {}", captures[1].to_uppercase()));- let camel = regex::Regex::new(r"([a-z0-9])([A-Z])").expect("valid");- let key = camel.replace_all(&key, "$1 $2");- let capitals = regex::Regex::new(r"([A-Z]+)([A-Z][a-z])").expect("valid");- let key = capitals.replace_all(&key, "$1 $2");+ let patterns = &*WORDIFY_PATTERNS;+ let key = patterns.dots.replace_all(key, |captures: ®ex::Captures| format!(" \u{203A} {}", captures[1].to_uppercase()));+ let key = patterns.camel.replace_all(&key, "$1 $2");+ let key = patterns.capitals.replace_all(&key, "$1 $2");let mut key = key.into_owned();if let Some(first) = key.chars().next().filter(char::is_ascii_lowercase) {key.replace_range(..1, &first.to_ascii_uppercase().to_string());}- let words = regex::Regex::new(r"\b\w+\b").expect("valid");- let mut key = words.replace_all(&key, |captures: ®ex::Captures| if KNOWN_ACRONYMS.contains(&captures[0].to_lowercase().as_str()) { captures[0].to_uppercase() } else { captures[0].to_string() }).into_owned();- for (term, replacement) in KNOWN_TERM_MAPPINGS {- let pattern = regex::RegexBuilder::new(&format!(r"\b{term}\b")).case_insensitive(true).build().expect("valid");+ let mut key = patterns.words.replace_all(&key, |captures: ®ex::Captures| if KNOWN_ACRONYMS.contains(&captures[0].to_lowercase().as_str()) { captures[0].to_uppercase() } else { captures[0].to_string() }).into_owned();+ for (pattern, replacement) in &patterns.terms {key = pattern.replace_all(&key, *replacement).into_owned();}key@@ -641,8 +656,12 @@ pub fn setting_key_to_display_format(key: &str, group_id: &str, is_language_tag_/// `trimCategoryForGroup`: drops the leading part of the category the group id already names.fn trim_category_for_group(category: &str, group_id: &str) -> String {- let insiders = regex::RegexBuilder::new("-?insiders$").case_insensitive(true).build().expect("valid");- let group_id = if category.to_lowercase().ends_with("insiders") { group_id.to_string() } else { insiders.replace(group_id, "").into_owned() };+ static INSIDERS: LazyLock<regex::Regex> = LazyLock::new(|| regex::RegexBuilder::new("-?insiders$").case_insensitive(true).build().expect("valid"));+ // Patterns come from group ids, a few hundred at most; compiling them per visible row cost a third of a scroll frame.+ thread_local! {+ static GROUP_PATTERNS: RefCell<HashMap<String, Option<regex::Regex>>> = RefCell::default();+ }+ let group_id = if category.to_lowercase().ends_with("insiders") { group_id.to_string() } else { INSIDERS.replace(group_id, "").into_owned() };let parts: Vec<String> = group_id.split('.').map(|part| {@@ -653,11 +672,13 @@ fn trim_category_for_group(category: &str, group_id: &str) -> String {for forward in [true, false] {let mut parts = parts.clone();while !parts.is_empty() {- let pattern = regex::RegexBuilder::new(&format!(r"^{}(\.|$)", parts.join(r"\."))).case_insensitive(true).build();- if let Ok(pattern) = pattern- && pattern.is_match(category)- {- return pattern.replace(category, "").into_owned();+ let source = format!(r"^{}(\.|$)", parts.join(r"\."));+ let trimmed = GROUP_PATTERNS.with_borrow_mut(|patterns| {+ let pattern = patterns.entry(source).or_insert_with_key(|source| regex::RegexBuilder::new(source).case_insensitive(true).build().ok());+ pattern.as_ref().filter(|pattern| pattern.is_match(category)).map(|pattern| pattern.replace(category, "").into_owned())+ });+ if let Some(trimmed) = trimmed {+ return trimmed;}if forward {parts.pop();diff --git a/native/crates/app/src/workbench/settings_editor_view/tests.rs b/native/crates/app/src/workbench/settings_editor_view/tests.rsindex e90131d8497..18895d8ce5d 100644--- a/native/crates/app/src/workbench/settings_editor_view/tests.rs+++ b/native/crates/app/src/workbench/settings_editor_view/tests.rs@@ -261,3 +261,57 @@ fn dragging_the_toc_sash_resizes_the_toc_and_stores_its_width(cx: &mut TestAppCocx.run_until_parked();assert_eq!(toc_width(&workbench, cx), 150., "reopening starts at the stored width");}++/// Frame time of a trackpad scroll through every setting (core and built-in extensions) in a 1440x900 window: each+/// frame is one 30px pixel wheel event, then the draw. Text is laid out by gpui's NoopTextSystem (CoreText needs the+/// main thread, which libtest never gives) and nothing reaches the GPU. The gate is 8 ms at the median and p95, a 120 Hz frame. Run in release:+/// `cargo test --release -p app -- --ignored settings_scroll_frame_time --nocapture`.+#[test]+#[ignore]+fn settings_scroll_frame_time() {+ use gpui::{AppContext, HeadlessAppContext, InputEvent, Modifiers, ScrollDelta, ScrollWheelEvent, TouchPhase, point, px, size};+ use std::time::Instant;+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();+ let theme = load_theme(&extensions, "Dark Modern").unwrap();+ let described: Vec<(&str, &Value)> = extensions.iter().map(|extension| (extension.id.as_str(), &extension.description)).collect();+ let dir = std::env::temp_dir().join(format!("code-gpui-settings-scroll-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("User")).unwrap();+ let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&described), dir.join("User"), None)));+ let languages = Languages::new(&extensions);+ let mut cx = HeadlessAppContext::new(Arc::new(gpui::NoopTextSystem));+ let window = cx+ .open_window(size(px(1440.), px(900.)), |_, cx| cx.new(|cx| Workbench::new(theme, app_root.clone(), None, languages, settings, HostSync::new(std::sync::mpsc::channel().0), cx)))+ .unwrap();+ let frame = |cx: &mut HeadlessAppContext, scroll: Option<f32>| {+ cx.update_window(window.into(), |_, window, cx| {+ let start = Instant::now();+ if let Some(dy) = scroll {+ let event = ScrollWheelEvent { position: point(px(900.), px(500.)), delta: ScrollDelta::Pixels(point(px(0.), px(-dy))), modifiers: Modifiers::none(), touch_phase: TouchPhase::Moved };+ window.dispatch_event(event.to_platform_input(), cx);+ }+ window.draw(cx).clear(cx);+ start.elapsed().as_secs_f64() * 1000.+ })+ .unwrap()+ };+ window+ .update(&mut cx, |workbench, window, cx| {+ drop(workbench.execute_command("workbench.action.openSettings2", Vec::new(), window, cx));+ // The whole tree, as after a cleared search, not Commonly Used alone.+ workbench.settings_editor.category = None;+ workbench.render_settings(cx);+ })+ .unwrap();+ cx.run_until_parked();+ frame(&mut cx, None);+ let rows = window.update(&mut cx, |workbench, _, _| workbench.settings_editor.rows.len()).unwrap();+ let mut times: Vec<f64> = (0..600).map(|_| frame(&mut cx, Some(30.))).collect();+ let scrolled = window.update(&mut cx, |workbench, _, _| workbench.settings_editor.tree.logical_scroll_top().item_ix).unwrap();+ std::fs::remove_dir_all(&dir).unwrap();+ assert!(scrolled > 100, "the tree scrolled to row {scrolled} of {rows}");+ times.sort_by(f64::total_cmp);+ let (median, p95, max) = (times[times.len() / 2], times[times.len() * 95 / 100], times[times.len() - 1]);+ eprintln!("{rows} rows, scrolled to row {scrolled}: median {median:.2} ms, p95 {p95:.2} ms, max {max:.2} ms");+ assert!(median < 8. && p95 < 8., "median {median:.2} ms, p95 {p95:.2} ms, the gate is 8 ms");+}