Skip to content

Commit 22111ed

Browse files
Optimize StandaloneCallTransformer._find_balanced_parens
The optimized code achieves a **26% runtime improvement** by replacing character-by-character iteration with regex-based scanning to find special characters (quotes, parentheses, backslashes). This optimization significantly reduces Python-level loop overhead by leveraging compiled regex's C-level string scanning. **Key optimization:** - **Original approach:** Iterates through every character in the string (108,802 iterations in profiling), checking each one against quotes and parentheses - **Optimized approach:** Uses `self._special_char_re.search()` to jump directly to the next relevant character, reducing iterations from ~109K to ~16.5K (85% reduction) **Why this is faster:** The regex engine scans through irrelevant characters (letters, numbers, whitespace, operators) at C speed, only stopping at characters that matter for parenthesis balancing. Line profiler shows the main while loop went from 110,858 hits (18.6% of time) to just 18,571 hits (8.2% of time). **Performance characteristics by workload:** - **Best speedups (100%+ faster):** Large inputs with long stretches of non-special characters benefit most. Tests like `test_large_many_simple_arguments` (1655% faster) and `test_large_object_and_array_literals_complex` (1485% faster) show dramatic improvements because regex can skip over lengthy argument lists and object literals in one jump. - **Moderate slowdowns (30-60%):** Small inputs with many special characters pay a regex overhead penalty. Each `regex.search()` call has setup cost, so when special characters are frequent (e.g., `test_deeply_nested_parens_1000` with 73% slower), the optimization's benefits are negated. - **Trade-off sweet spot:** The optimization excels when the function is called on realistic JavaScript code with long argument lists, string literals, or object/array structures—common in test instrumentation scenarios. **Impact on workloads:** Given that `StandaloneCallTransformer` instruments JavaScript test code by finding function call boundaries, the typical use case involves parsing moderate-to-large code snippets with mixed content (strings, nested calls, object literals). The 26% average improvement suggests real-world code has enough non-special character sequences to benefit from regex scanning, making this optimization valuable for the hot path of JavaScript test instrumentation.
1 parent f5dd109 commit 22111ed

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

codeflash/languages/javascript/instrument.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ def __init__(self, function_to_optimize: FunctionToOptimize, capture_func: str)
128128
rf"(\s*)(await\s+)?(\w+)\[['\"]({re.escape(self.func_name)})['\"]]\s*\("
129129
)
130130

131+
# Compiled regex to find the next character of interest (quotes, parentheses, backslash).
132+
# This lets us skip large stretches of irrelevant characters in C instead of Python.
133+
self._special_char_re = re.compile(r'["\'`()\\]')
134+
131135
def transform(self, code: str) -> str:
132136
"""Transform all standalone calls in the code."""
133137
result: list[str] = []
@@ -327,13 +331,21 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N
327331
s_len = len(s)
328332
quotes = "\"'`"
329333

334+
special_re = self._special_char_re
335+
336+
# Use regex to jump to the next special character (quote, parenthesis, backslash).
337+
# This reduces Python-level iterations by leveraging C-level scanning.
330338
while pos < s_len and depth > 0:
331-
char = s[pos]
339+
m = special_re.search(s, pos)
340+
if not m:
341+
return None, -1
342+
i = m.start()
343+
char = m.group(0)
332344

333345
# Handle string literals
334346
# Note: preserve original escaping semantics (only checks immediate preceding char)
335347
if char in quotes:
336-
prev_char = s[pos - 1] if pos > 0 else None
348+
prev_char = s[i - 1] if i > 0 else None
337349
if prev_char != "\\":
338350
if not in_string:
339351
in_string = True
@@ -347,7 +359,8 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N
347359
elif char == ")":
348360
depth -= 1
349361

350-
pos += 1
362+
pos = i + 1
363+
351364

352365
if depth != 0:
353366
return None, -1

0 commit comments

Comments
 (0)