From 4ded712dbde5c335abf768d11ebd209be4d4d487 Mon Sep 17 00:00:00 2001
From: RoloEdits <RoloEdits@gmail.com>
Date: Thu, 23 Jan 2025 15:49:14 -0800
Subject: [PATCH] perf(syntax): short-circuit if name matches `language_id`
 (#12407)

---
 helix-core/src/syntax.rs | 19 +++++++++++++++----
 1 file changed, 15 insertions(+), 4 deletions(-)

diff --git a/helix-core/src/syntax.rs b/helix-core/src/syntax.rs
index 76bee1fd..852a9752 100644
--- a/helix-core/src/syntax.rs
+++ b/helix-core/src/syntax.rs
@@ -994,16 +994,27 @@ impl Loader {
             .cloned()
     }
 
-    pub fn language_config_for_language_id(&self, id: &str) -> Option<Arc<LanguageConfiguration>> {
+    pub fn language_config_for_language_id(
+        &self,
+        id: impl PartialEq<String>,
+    ) -> Option<Arc<LanguageConfiguration>> {
         self.language_configs
             .iter()
-            .find(|config| config.language_id == id)
+            .find(|config| id.eq(&config.language_id))
             .cloned()
     }
 
-    /// Unlike language_config_for_language_id, which only returns Some for an exact id, this
+    /// Unlike `language_config_for_language_id`, which only returns Some for an exact id, this
     /// function will perform a regex match on the given string to find the closest language match.
     pub fn language_config_for_name(&self, slice: RopeSlice) -> Option<Arc<LanguageConfiguration>> {
+        // PERF: If the name matches up with the id, then this saves the need to do expensive regex.
+        let shortcircuit = self.language_config_for_language_id(slice);
+        if shortcircuit.is_some() {
+            return shortcircuit;
+        }
+
+        // If the name did not match up with a known id, then match on injection regex.
+
         let mut best_match_length = 0;
         let mut best_match_position = None;
         for (i, configuration) in self.language_configs.iter().enumerate() {
@@ -1026,7 +1037,7 @@ impl Loader {
         capture: &InjectionLanguageMarker,
     ) -> Option<Arc<LanguageConfiguration>> {
         match capture {
-            InjectionLanguageMarker::LanguageId(id) => self.language_config_for_language_id(id),
+            InjectionLanguageMarker::LanguageId(id) => self.language_config_for_language_id(*id),
             InjectionLanguageMarker::Name(name) => self.language_config_for_name(*name),
             InjectionLanguageMarker::Filename(file) => {
                 let path_str: Cow<str> = (*file).into();