⚡️ Speed up function marshal_json by 358%#126
Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Open
Conversation
The optimized code achieves a **358% speedup** through two key optimizations: **1. Pydantic Model Caching (Primary optimization)** - Added `_marshaller_cache` to store created Pydantic models by type - The original code called `create_model()` on every invocation, which is extremely expensive (93.5% of total runtime in profiler) - Caching reduces `create_model` calls from 70 hits to only 31 hits for new types, with cached lookups being ~1000x faster - This optimization is most effective for **repeated serialization of the same types**, as shown in the test results where basic type serializations see 15-40x speedups **2. Direct Dictionary Access** - Replaced `d[next(iter(d))]` with direct `d["body"]` access - Since `model_dump()` always creates a dict with a single "body" key, direct access eliminates iterator overhead - Minor but consistent improvement across all test cases **3. Micro-optimization in `is_nullable`** - Cached `get_origin(arg)` result to avoid redundant calls in the loop - Small but measurable improvement in type checking **Performance characteristics:** - **Basic types**: 15-40x speedup due to model caching eliminating expensive Pydantic model creation - **Large data structures**: 3-6x speedup as serialization overhead becomes more significant relative to model creation - **Cache hits**: Near-instant model lookup vs. expensive `create_model()` call - **Best for**: Applications that repeatedly serialize the same types, which is common in API serialization workflows The caching strategy is particularly effective because type objects are hashable and immutable, making them ideal cache keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.