Skip to content

Commit 2d36dd4

Browse files
committed
⚡ Bolt: Cache lexicon regex patterns to reduce compilation overhead
Implemented an explicit dictionary cache for compiled regex patterns in `KokoroEngine.apply_lexicon`. This avoids recompiling regex patterns on every call for every text segment, which significantly improves performance and prevents evicting Python's internal regex cache when processing large documents with extensive lexicons.
1 parent 54776c0 commit 2d36dd4

2 files changed

Lines changed: 9 additions & 2 deletions

File tree

.jules/bolt.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## 2025-02-12 - Explicit Regex Caching in Tight Loops
2+
**Learning:** Python has an internal cache for compiled regex patterns (usually up to 512 entries). However, dynamically compiling a large number of varying regex patterns in tight loops can quickly evict entries, leading to silent performance degradation as patterns are constantly recompiled. In `kokoro_engine.py`, `apply_lexicon` was compiling regex patterns on every single lexicon entry for every text segment processed, introducing measurable overhead during large document generation.
3+
**Action:** When performing regex-based text replacements with dynamic or user-provided mappings (like lexicons), explicitly cache the `re.compile()` objects in a class attribute or dictionary. This avoids recompilation overhead when processing large or split text blocks where the same lexicon mappings are used repeatedly.

kokoro_engine.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ def __init__(self):
7777
if not os.path.exists(CACHE_DIR):
7878
os.makedirs(CACHE_DIR)
7979

80+
self._lexicon_cache = {} # Cache for compiled regex patterns
81+
8082
# Callbacks
8183
self.on_progress = None # func(percentage, time_elapsed, eta, detail_text)
8284
self.on_status = None # func(msg, is_error)
@@ -93,8 +95,10 @@ def apply_lexicon(self, text, lexicon):
9395
for src, dest in lexicon.items():
9496
if not src: continue
9597
try:
96-
# Escape the search term to treat it as literal text
97-
pattern = re.compile(re.escape(src), re.IGNORECASE)
98+
if src not in self._lexicon_cache:
99+
# Escape the search term to treat it as literal text
100+
self._lexicon_cache[src] = re.compile(re.escape(src), re.IGNORECASE)
101+
pattern = self._lexicon_cache[src]
98102
text = pattern.sub(dest, text)
99103
except Exception as e:
100104
print(f"Lexicon error for '{src}': {e}")

0 commit comments

Comments
 (0)