⚡️ Speed up function can_set_locale by 13%
#90
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.
📄 13% (0.13x) speedup for
can_set_localeinpandas/_config/localization.py⏱️ Runtime :
50.3 milliseconds→44.5 milliseconds(best of62runs)📝 Explanation and details
The optimization achieves a 12% speedup through two key changes:
1. String concatenation optimization in
set_locale:Replaced f-string formatting
f"{normalized_code}.{normalized_encoding}"with direct concatenationnormalized_code + '.' + normalized_encoding. While f-strings are generally fast, direct concatenation avoids the overhead of format string parsing for this simple case.2. Context manager elimination in
can_set_locale:The most significant optimization replaces the
with set_locale(lc, lc_var=lc_var):context manager call with directtry/finallylogic. This eliminates:set_locale@contextmanagerdecoratorPerformance characteristics:
The optimization is most effective for scenarios with frequent
can_set_localecalls, showing 15-58% improvements on invalid locales and 19-45% on valid ones. The direct approach is particularly beneficial when testing many locales in batch operations, as seen in the stress tests showing 15-36% improvements across 1000+ iterations.The changes maintain identical behavior and error handling while reducing the call stack depth and computational overhead for this boolean validation function.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
config/test_localization.py::test_can_set_current_localeconfig/test_localization.py::test_can_set_locale_invalid_getconfig/test_localization.py::test_can_set_locale_invalid_setconfig/test_localization.py::test_can_set_locale_no_leakconfig/test_localization.py::test_can_set_locale_valid_setio/json/test_ujson.py::TestUltraJSONTests.test_encode_non_c_locale🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-can_set_locale-mhbmmfkjand push.