Skip to content

Commit 29bffe9

Browse files
⚡️ Speed up function function_is_a_property by 60% (#974)
* Optimize function_is_a_property The optimized version achieves a **60% speedup** by replacing Python's `any()` generator expression with a manual loop and making three key micro-optimizations: **What was optimized:** 1. **Replaced `isinstance()` with `type() is`**: Direct type comparison (`type(node) is ast_Name`) is faster than `isinstance(node, ast.Name)` for AST nodes where subclassing is rare 2. **Eliminated repeated lookups**: Cached `"property"` as `property_id` and `ast.Name` as `ast_Name` in local variables to avoid global/attribute lookups in the loop 3. **Manual loop with early return**: Replaced `any()` generator with explicit `for` loop that returns `True` immediately upon finding a match, avoiding generator overhead **Why it's faster:** - The `any()` function creates generator machinery that adds overhead, especially for small decorator lists - `isinstance()` performs multiple checks while `type() is` does a single identity comparison - Local variable access is significantly faster than repeated global/attribute lookups in tight loops **Performance characteristics from tests:** - **Small decorator lists** (1-3 decorators): 50-80% faster due to reduced per-iteration overhead - **Large decorator lists** (1000+ decorators): 55-60% consistent speedup, with early termination providing additional benefits when `@property` appears early - **Empty decorator lists**: 77% faster due to avoiding `any()` generator setup entirely **Impact on workloads:** Based on the function references, this function is called during AST traversal in `visit_FunctionDef` and `visit_AsyncFunctionDef` methods - likely part of a code analysis pipeline that processes many functions. The 60% speedup will be particularly beneficial when analyzing codebases with many decorated functions, as this optimization reduces overhead in a hot path that's called once per function definition. * format --------- Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Kevin Turcios <[email protected]>
1 parent e8fba39 commit 29bffe9

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

codeflash/discovery/functions_to_optimize.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,4 +774,9 @@ def function_has_return_statement(function_node: FunctionDef | AsyncFunctionDef)
774774

775775

776776
def function_is_a_property(function_node: FunctionDef | AsyncFunctionDef) -> bool:
777-
return any(isinstance(node, ast.Name) and node.id == "property" for node in function_node.decorator_list)
777+
property_id = "property"
778+
ast_name = ast.Name
779+
for node in function_node.decorator_list: # noqa: SIM110
780+
if type(node) is ast_name and node.id == property_id:
781+
return True
782+
return False

0 commit comments

Comments
 (0)