Skip to content

Commit 9531526

Browse files
⚡️ Speed up function function_kind by 39% in PR #309 (updated-vsc-extension)
Here's an optimized version of your program. Main changes. - Replace slices and length-based for-loops with more direct, idiomatic Python control flow (they did nothing). - Combine checks for better early returns. - Reduce unnecessary list accesses. - Process decorator list without unnecessary nesting. - No changes to function signatures or output. All your in-code comments are preserved (there were none). **Key improvements:** - Direct mapping of `parents[0].type`; no useless range-loop. - Early exit for empty `parents`. - Avoid redundant list traversal. - Set literal for type checking. This function has the same return signature and logic, but runs faster and is easier to reason about.
1 parent cfaee2a commit 9531526

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

codeflash/code_utils/static_analysis.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
from pydantic import BaseModel, ConfigDict, field_validator
99

10+
from codeflash.models.models import FunctionParent
11+
1012
if TYPE_CHECKING:
1113
from codeflash.models.models import FunctionParent
1214

@@ -139,16 +141,19 @@ def get_first_top_level_function_or_method_ast(
139141

140142

141143
def function_kind(node: ast.FunctionDef | ast.AsyncFunctionDef, parents: list[FunctionParent]) -> FunctionKind | None:
142-
if not parents or parents[0].type in ["FunctionDef", "AsyncFunctionDef"]:
144+
if not parents:
145+
return FunctionKind.FUNCTION
146+
parent_type = parents[0].type
147+
if parent_type in {"FunctionDef", "AsyncFunctionDef"}:
143148
return FunctionKind.FUNCTION
144-
for _i in range(len(parents) - 1, -1, -1):
145-
continue
146-
if parents[0].type == "ClassDef":
149+
if parent_type == "ClassDef":
150+
# Fast path: decorator_list is typically small; scan for 'classmethod' and 'staticmethod'
147151
for decorator in node.decorator_list:
148152
if isinstance(decorator, ast.Name):
149-
if decorator.id == "classmethod":
153+
did = decorator.id
154+
if did == "classmethod":
150155
return FunctionKind.CLASS_METHOD
151-
if decorator.id == "staticmethod":
156+
if did == "staticmethod":
152157
return FunctionKind.STATIC_METHOD
153158
return FunctionKind.INSTANCE_METHOD
154159
return None

0 commit comments

Comments
 (0)