⚡️ Speed up method _DocxPartitioner._style_based_element_type by 593%
#61
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.
📄 593% (5.93x) speedup for
_DocxPartitioner._style_based_element_typeinunstructured/partition/docx.py⏱️ Runtime :
5.53 milliseconds→798 microseconds(best of116runs)📝 Explanation and details
The optimization achieves a 593% speedup by moving the
STYLE_TO_ELEMENT_MAPPINGdictionary from inside the method to module level as a global constant.What changed:
_style_based_element_type()to the module level asSTYLE_TO_ELEMENT_MAPPINGWhy this is dramatically faster:
The original code was reconstructing a 29-entry dictionary on every single method invocation. The line profiler shows this dictionary creation consumed 58.7% of total execution time (33.7ms out of 57.6ms total). Each dictionary entry required individual object creation and insertion operations, creating significant overhead when called repeatedly.
By moving the dictionary to module level, it's constructed only once when the module is imported, eliminating this repeated work entirely. The optimized version shows the dictionary lookup now takes only 53.3% of the much smaller total time.
Performance characteristics:
This optimization is especially valuable for document processing workloads where
_style_based_element_type()is called repeatedly for each paragraph in potentially large documents, making the cumulative time savings substantial.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_DocxPartitioner._style_based_element_type-mjdwusewand push.