⚡️ Speed up function _maybe_wrap_formatter by 35%
#384
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.
📄 35% (0.35x) speedup for
_maybe_wrap_formatterinpandas/io/formats/style_render.py⏱️ Runtime :
223 microseconds→164 microseconds(best of183runs)📝 Explanation and details
The optimization achieves a 35% speedup through targeted fast-path optimizations and reduced function call overhead:
Key Optimizations:
get_optionFast Path: Added a direct lookup optimization for common option patterns. Instead of always calling_get_single_key()and_get_root()(which handle regex matching and validation), the code now:_global_configlookup_default_formatterString Creation: Moved f-string template creation outside the formatting call to avoid repeated string construction, reducing per-call overhead for float/complex formatting._maybe_wrap_formatterClosure Optimization:get_option()call with explicit if-else to avoid the expensive config lookup when precision is already providedna_repwrapper, created a function with default parameters to avoid repeated attribute lookups in the closurePerformance Impact Based on Tests:
formatter=Noneandget_option()is called, as the fast-path config lookup dramatically reduces overheadHot Path Relevance: The function references show
_maybe_wrap_formatteris called in pandas styling operations (format(),format_index(),format_index_names()) which are frequently used in data presentation workflows, making these optimizations particularly valuable for styling-heavy applications.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_maybe_wrap_formatter-mio6rkw9and push.