⚡️ Speed up method CallInputs.from_interface
by 6%
#49
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.
📄 6% (0.06x) speedup for
CallInputs.from_interface
inguardrails/classes/history/call_inputs.py
⏱️ Runtime :
1.24 milliseconds
→1.17 milliseconds
(best of65
runs)📝 Explanation and details
The optimized version achieves a 5% speedup by eliminating repeated attribute access on the
i_call_inputs
object.Key optimizations:
Local variable caching: Instead of accessing
i_call_inputs.attribute
multiple times (once during assignment in thecls()
call), attributes are accessed once and stored in local variables. This reduces attribute lookup overhead, which can be significant for objects with complex attribute resolution.Simplified conditional logic: The original code used
(i_call_inputs.args or [])
which involves both attribute access and a boolean evaluation. The optimized version usesargs_val if args_val is not None else []
, which is more explicit and slightly faster since it avoids theor
operator's truthiness evaluation.Performance characteristics from tests:
The optimization is particularly effective for this use case because the
from_interface
method performs many sequential attribute accesses on the same object, making local caching a worthwhile micro-optimization.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
test_pytest_testsunit_teststest_guard_log_py_testsintegration_teststest_guard_py_testsunit_testsvalidator__replay_test_0.py::test_guardrails_classes_history_call_inputs_CallInputs_from_interface
To edit these changes
git checkout codeflash/optimize-CallInputs.from_interface-mh1kmf2u
and push.