⚡️ Speed up method CustomGuardrail._event_hook_is_event_type by 278%
#181
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.
📄 278% (2.78x) speedup for
CustomGuardrail._event_hook_is_event_typeinlitellm/integrations/custom_guardrail.py⏱️ Runtime :
3.70 milliseconds→977 microseconds(best of168runs)📝 Explanation and details
The optimized code achieves a 278% speedup by implementing strategic caching to eliminate redundant work in membership tests:
Key optimizations:
Local variable caching: Store
self.event_hookandevent_type.valuein local variables to avoid repeated attribute lookups, reducing overhead from ~315ns to ~251ns per access.Set-based membership for lists: When
event_hookis a list, cache it as a set (self._event_hook_set) for O(1) lookups instead of O(n) linear scans. The cache is invalidated when the source list changes, tracked viaself._event_hook_set_source.Mode tag value caching: For Mode objects, pre-compute and cache tag values as a set (
_tags_value_set) directly on the Mode instance, converting O(n) membership tests to O(1).Performance impact by test type:
The optimization is most effective for applications that repeatedly call
_event_hook_is_event_typewith the same CustomGuardrail instance, particularly when dealing with large event hook lists where the caching overhead is amortized across many lookups.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_zbim32de/tmp0cz6uli5/test_concolic_coverage.py::test_CustomGuardrail__event_hook_is_event_typecodeflash_concolic_zbim32de/tmp0cz6uli5/test_concolic_coverage.py::test_CustomGuardrail__event_hook_is_event_type_2codeflash_concolic_zbim32de/tmp0cz6uli5/test_concolic_coverage.py::test_CustomGuardrail__event_hook_is_event_type_3codeflash_concolic_zbim32de/tmp0cz6uli5/test_concolic_coverage.py::test_CustomGuardrail__event_hook_is_event_type_4To edit these changes
git checkout codeflash/optimize-CustomGuardrail._event_hook_is_event_type-mhdwmyk7and push.