Skip to content

Commit 2832845

Browse files
authored
Merge pull request #1588 from codeflash-ai/codeflash/optimize-pr1561-2026-02-20T07.28.03
⚡️ Speed up function `_insert_after_imports` by 3,622% in PR #1561 (`add/support_react`)
2 parents 3b5a5c7 + f9e4ea2 commit 2832845

2 files changed

Lines changed: 18 additions & 10 deletions

File tree

codeflash/languages/javascript/frameworks/react/profiler.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -217,18 +217,24 @@ def _insert_after_imports(source: str, code: str, analyzer: TreeSitterAnalyzer)
217217
tree = analyzer.parse(source_bytes)
218218

219219
last_import_end = 0
220-
for child in tree.root_node.children:
220+
# Search from the end and stop at the first import_statement encountered
221+
# to avoid scanning all children when the last import is near the end.
222+
for child in reversed(tree.root_node.children):
221223
if child.type == "import_statement":
222224
last_import_end = child.end_byte
225+
break
226+
227+
# Find end of line after last import using byte offsets to match tree-sitter.
228+
nl_pos = source_bytes.find(b"\n", last_import_end)
229+
if nl_pos == -1:
230+
insert_pos = len(source_bytes)
231+
else:
232+
insert_pos = nl_pos + 1 # skip the newline
223233

224-
# Find end of line after last import
225-
insert_pos = last_import_end
226-
while insert_pos < len(source) and source[insert_pos] != "\n":
227-
insert_pos += 1
228-
if insert_pos < len(source):
229-
insert_pos += 1 # skip the newline
234+
code_bytes = code.encode("utf-8")
235+
new_bytes = source_bytes[:insert_pos] + b"\n" + code_bytes + b"\n\n" + source_bytes[insert_pos:]
230236

231-
return source[:insert_pos] + "\n" + code + "\n\n" + source[insert_pos:]
237+
return new_bytes.decode("utf-8")
232238

233239

234240
def _ensure_react_import(source: str) -> str:

codeflash/languages/javascript/treesitter.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,10 @@ def parse(self, source: str | bytes) -> Tree:
162162
163163
"""
164164
if isinstance(source, str):
165-
source = source.encode("utf8")
166-
return self.parser.parse(source)
165+
source_bytes = source.encode("utf8")
166+
else:
167+
source_bytes = source
168+
return self.parser.parse(source_bytes)
167169

168170
def get_node_text(self, node: Node, source: bytes) -> str:
169171
"""Extract the source text for a tree-sitter node.

0 commit comments

Comments
 (0)