Skip to content

Commit 0630303

Browse files
⚡️ Speed up function create_wrapper_function by 14% in PR #617 (alpha-async)
The optimized code achieves a **13% speedup** by eliminating redundant AST node creation through **aggressive caching and reuse**. **What specific optimizations were applied:** 1. **Pre-constructed AST node cache**: Instead of creating new `ast.Name` and `ast.Attribute` objects repeatedly (the original created hundreds of identical nodes), the optimized version creates each unique node once and reuses it. For example, `n_test_module_name_L = name("test_module_name", LOAD)` is created once and reused everywhere. 2. **Constant node reuse**: Common constants like `ast.Constant(value=":")` are created once as `c_colon` and reused throughout, eliminating duplicate allocations. 3. **Factory functions for complex structures**: `JoinedStr` constructions are moved into reusable factory functions like `joinedstr_test_id()`, reducing code duplication and enabling better optimization. **Why this leads to speedup:** - **Reduced object allocation overhead**: The original code was creating ~200+ identical AST nodes per call. The optimized version creates each unique node exactly once. - **Better memory locality**: Reusing the same objects improves CPU cache efficiency. - **Fewer function calls**: Instead of calling `ast.Name()` hundreds of times, it's called once per unique identifier. **Test case performance patterns:** The optimization shows consistent 15-20% improvements across most test cases, with particularly strong gains in tests that exercise the full AST construction pipeline (like `test_assigns_test_id` showing 19% improvement). The speedup is most pronounced for tests that trigger the complex `JoinedStr` constructions, which benefited most from the caching strategy. This optimization is especially effective for workloads that call `create_wrapper_function` repeatedly, as the AST node reuse compound the benefits over multiple invocations.
1 parent 7c53b19 commit 0630303

File tree

1 file changed

+314
-271
lines changed

1 file changed

+314
-271
lines changed

0 commit comments

Comments
 (0)