⚡️ Speed up function marshal_json by 358%
#126
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.
📄 358% (3.58x) speedup for
marshal_jsoninsrc/mistralai/utils/serializers.py⏱️ Runtime :
25.2 milliseconds→5.50 milliseconds(best of57runs)📝 Explanation and details
The optimized code achieves a 358% speedup through two key optimizations:
1. Pydantic Model Caching (Primary optimization)
_marshaller_cacheto store created Pydantic models by typecreate_model()on every invocation, which is extremely expensive (93.5% of total runtime in profiler)create_modelcalls from 70 hits to only 31 hits for new types, with cached lookups being ~1000x faster2. Direct Dictionary Access
d[next(iter(d))]with directd["body"]accessmodel_dump()always creates a dict with a single "body" key, direct access eliminates iterator overhead3. Micro-optimization in
is_nullableget_origin(arg)result to avoid redundant calls in the loopPerformance characteristics:
create_model()callThe caching strategy is particularly effective because type objects are hashable and immutable, making them ideal cache keys.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-marshal_json-mh4k0i53and push.