From 84a3ebcaa1dd626781d824c3e8c4da225101d806 Mon Sep 17 00:00:00 2001 From: LeanBitLab <245915690+LeanBitLab@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:10:43 +0000 Subject: [PATCH] Performance: Pre-compile Regex in String.splitOnWhitespace `StringUtils.splitOnWhitespace()` created a new `Regex("\\s+")` instance every time it was called. Because it is used in various text processing and dictionary-filtering paths, pre-compiling this to a single, static property eliminates unnecessary regex compilation overhead and avoids useless GC pressure during fast typing/searching. --- .jules/bolt.md | 4 ++++ .../main/java/helium314/keyboard/latin/common/StringUtils.kt | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.jules/bolt.md b/.jules/bolt.md index 5d54a29f7..77119f7cb 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -1,3 +1,7 @@ ## 2024-05-18 - Language Detector Optimization **Learning:** `LanguageDetector.detect` uses `Regex("[^\\p{L}]+")` inside `detectByHeuristics`, creating a new Regex instance on every call. This method is called via `ProofreadHelper` which is likely triggered on user typing or interaction. Pre-compiling the Regex as a top-level constant avoids the overhead of regex compilation for every detection call. **Action:** Always check for repeated Regex instantiations in frequently called string processing or detection methods and extract them to top-level or companion object properties. + +## 2024-05-18 - StringUtils Whitespace Split Optimization +**Learning:** `StringUtils.splitOnWhitespace` creates a `Regex("\\s+")` inline every time it is called. Since this is an extension function used across settings and text processing, this causes unnecessary allocations. +**Action:** Abstract frequent inline regex usages into `private val` properties at the object or file level to avoid repeated regex compilation. diff --git a/app/src/main/java/helium314/keyboard/latin/common/StringUtils.kt b/app/src/main/java/helium314/keyboard/latin/common/StringUtils.kt index 51c6edfdd..d0360ff21 100644 --- a/app/src/main/java/helium314/keyboard/latin/common/StringUtils.kt +++ b/app/src/main/java/helium314/keyboard/latin/common/StringUtils.kt @@ -291,7 +291,8 @@ fun isEmoji(c: Int): Boolean = StringUtils.mightBeEmoji(c) && isEmoji(StringUtil /** returns whether the text is a single emoji */ fun isEmoji(text: CharSequence): Boolean = mightBeEmoji(text) && text.matches(emoRegex) -fun String.splitOnWhitespace() = split(Regex("\\s+")).filter { it.isNotEmpty() } +private val WHITESPACE_REGEX = Regex("\\s+") +fun String.splitOnWhitespace() = split(WHITESPACE_REGEX).filter { it.isNotEmpty() } // from https://github.com/mathiasbynens/emoji-test-regex-pattern, MIT license // matches single emojis only