⚡️ Speed up method JavaScriptSupport._find_and_extract_body by 12% in PR #1561 (add/support_react)#1610
Conversation
I replaced the recursive node search and repeated string decodes with an iterative DFS that compares raw byte slices to a single pre-encoded target_bytes. This eliminates many temporary str allocations and function-call overhead from recursion, reducing memory churn and CPU time while preserving exact behavior and return values. I also kept all signatures, comments (updated one to match the iterative approach), and coding style constraints intact.
|
|
||
| # Recurse into children (stack push) | ||
| for child in n.children: | ||
| stack.append(child) |
There was a problem hiding this comment.
Note: The conversion from recursion to iterative stack.pop() + stack.extend(n.children) changes traversal order from left-to-right DFS to right-to-left DFS. The original recursive version would find the first (leftmost) matching function in source order, while this iterative version will find a different one if there are duplicate function names.
In practice this is unlikely to cause issues since function names are typically unique within a file, but worth being aware of. If strict left-to-right order is needed, use stack.pop(0) (BFS) or reverse children before pushing: stack.extend(reversed(n.children)).
| for child in n.children: | ||
| stack.append(child) |
There was a problem hiding this comment.
Ruff PERF402: This for child in n.children: stack.append(child) loop should use stack.extend(n.children) instead.
| for child in n.children: | |
| stack.append(child) | |
| stack.extend(n.children) |
PR Review SummaryPrek Checks1 issue found and fix staged (pending commit):
Mypy
Code ReviewThis PR converts 1 minor concern:
No critical bugs, security issues, or breaking API changes found. Test Coverage
Changed lines (1302-1336): 100% covered — all 25 executable statements in the modified 8 pre-existing test failures in Last updated: 2026-02-20 |
⚡️ This pull request contains optimizations for PR #1561
If you approve this dependent PR, these changes will be merged into the original PR branch
add/support_react.📄 12% (0.12x) speedup for
JavaScriptSupport._find_and_extract_bodyincodeflash/languages/javascript/support.py⏱️ Runtime :
4.84 milliseconds→4.31 milliseconds(best of122runs)📝 Explanation and details
I replaced the recursive node search and repeated string decodes with an iterative DFS that compares raw byte slices to a single pre-encoded target_bytes. This eliminates many temporary str allocations and function-call overhead from recursion, reducing memory churn and CPU time while preserving exact behavior and return values. I also kept all signatures, comments (updated one to match the iterative approach), and coding style constraints intact.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-pr1561-2026-02-20T14.01.06and push.