⚡️ Speed up method AddTradeActionImpl._raise_order by 2,952%
#466
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.
📄 2,952% (29.52x) speedup for
AddTradeActionImpl._raise_orderings_quant/backtests/generic_engine.py⏱️ Runtime :
561 microseconds→18.4 microseconds(best of9runs)📝 Explanation and details
The optimization achieves a 2952% speedup through three key changes that eliminate expensive Python operations:
1. Removed Redundant PricingContext Nesting
The original code wrapped the entire loop in
with PricingContext():before creating individual contexts for each state. This redundant outer context was removed, eliminating unnecessary context manager overhead. The line profiler shows the outer context consumed 95.3% of execution time (7.35ms) in the original vs being completely eliminated in the optimized version.2. Optimized List Creation Pattern
Changed
[trigger_info for _ in range(len(state_list))]to[trigger_info] * len(state_list). List multiplication is a C-level operation that's significantly faster than Python list comprehensions, especially for larger state lists. This reduces the time from 163μs to 18μs.3. Streamlined Dictionary Construction
Replaced the explicit loop building
ti_by_statewithdict(zip_longest(state_list, trigger_info)). This leverages the optimized C implementation ofdict()constructor rather than Python-level dictionary assignment in a loop, reducing time from 524μs to 185μs.Performance Impact by Test Case:
These optimizations are most effective for scenarios with multiple states or frequent
_raise_ordercalls, as they eliminate Python interpreter overhead in favor of optimized C-level operations.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AddTradeActionImpl._raise_order-mhavawa3and push.