⚡️ Speed up method ScopedVisitor.visit_Global by 218%
#487
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 218% (2.18x) speedup for
ScopedVisitor.visit_Globalinmarimo/_ast/visitor.py⏱️ Runtime :
16.3 milliseconds→5.13 milliseconds(best of275runs)📝 Explanation and details
The optimized code achieves a 218% speedup through three key optimizations:
1. Replaced
any()withinoperator inBlock.is_defined()return any(name == defn for defn in self.defs)return name in self.defsis_defined()runtime from 91.8ms to 1.1ms (~83x faster)2. Used
dict.setdefault()instead of conditional dictionary initializationif name not in self._refs: self._refs[name] = []refs_name = self._refs.setdefault(name, [])3. Added early
breakin reference search loopbreakafter finding matching reference in_add_ref()4. Cached repeated attribute lookups in
visit_Global()self.block_stack[-1]andself.block_stack[0]in local variablesThe optimizations are particularly effective for:
is_defined()check dramatically reduces overheadThe
is_defined()optimization provides the largest impact since it's called for every global name to check if it's already defined in the global scope.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_o_lbxivc/tmpvun_gdqb/test_concolic_coverage.py::test_ScopedVisitor_visit_GlobalTo edit these changes
git checkout codeflash/optimize-ScopedVisitor.visit_Global-mhcya60wand push.