⚡️ Speed up function rail_string_to_schema by 61%
#61
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.
📄 61% (0.61x) speedup for
rail_string_to_schemainguardrails/schema/rail_schema.py⏱️ Runtime :
34.4 milliseconds→21.4 milliseconds(best of28runs)📝 Explanation and details
The optimized code achieves a 60% speedup by implementing two key optimizations:
1. Pre-cached ValidationType instances (
_VALIDATION_TYPE_MAPPING)The original code creates a new
ValidationTypeobject for each schema element, which is expensive. The optimization introduces a module-level cache that pre-creates these instances:This eliminates repeated object construction - from the profiler, we can see ValidationType creation time drops from ~28ms to ~0.2ms across all calls.
2. Optimized xml_to_string calls
The original code calls
xml_to_string()on every attribute access, even when the attribute is already a string or None. The optimization adds type checks to avoid unnecessary conversions:Performance Impact by Test Case:
The optimizations are most effective for schemas with many elements that require type validation, which represents the common use case for this XML schema parsing functionality.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
unit_tests/actions/test_reask.py::test_get_reask_promptunit_tests/test_rail.py::test_format_not_read_as_validatorsunit_tests/test_rail.py::test_rail_list_with_listunit_tests/test_rail.py::test_rail_list_with_objectunit_tests/test_rail.py::test_rail_list_with_scalarunit_tests/test_rail.py::test_rail_object_with_listunit_tests/test_rail.py::test_rail_object_with_objectunit_tests/test_rail.py::test_rail_object_with_scalarunit_tests/test_rail.py::test_rail_outermost_listunit_tests/test_rail.py::test_rail_scalar_stringunit_tests/test_rail.py::test_rail_with_messagesunit_tests/test_skeleton.py::test_skeleton🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-rail_string_to_schema-mh1sqc68and push.