⚡️ Speed up function json_safe by 32%
#25
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.
📄 32% (0.32x) speedup for
json_safeinsrc/anthropic/_utils/_utils.py⏱️ Runtime :
23.6 milliseconds→17.9 milliseconds(best of96runs)📝 Explanation and details
The optimization achieves a 31% speedup by reordering the conditional checks in the
json_safefunction to prioritize the most efficient path for datetime/date objects.Key Change: The
isinstance(data, (datetime, date))check is moved from the bottom to the top of the conditional chain.Why This Works:
isoformat()call and early return, avoiding the more expensiveis_mapping()andis_iterable()function callsis_mapping()(26,278 hits) andis_iterable()(25,027 hits). The optimized version reduces these to 18,149 and 16,898 hits respectivelyPerformance by Test Case Type:
test_large_list_of_datesgoes from 1.01ms to 262μs)The optimization is particularly effective for JSON serialization scenarios where date/datetime objects are common, which aligns with the function's purpose of translating data "in the same fashion as
pydanticv2'smodel_dump(mode="json")".✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_6zuacb2h/tmpor0tq1if/test_concolic_coverage.py::test_json_safe_2To edit these changes
git checkout codeflash/optimize-json_safe-mhe1zwcband push.