⚡️ Speed up method AdvancedPdfLoader._format_table_element by 34%
#53
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.
📄 34% (0.34x) speedup for
AdvancedPdfLoader._format_table_elementincognee/infrastructure/loaders/external/advanced_pdf_loader.py⏱️ Runtime :
205 microseconds→153 microseconds(best of95runs)📝 Explanation and details
The optimized code achieves a 33% speedup by eliminating unnecessary function calls and optimizing string handling in the hot path.
Key optimizations:
Function call elimination: The original code always called
self._clean_text()even whentable_htmlwas available and would be returned immediately. The optimized version moves the text cleaning logic inline and only executes it when needed (whentable_htmlis falsy), avoiding 214 unnecessary function calls based on the profiler data.Lazy text processing: Instead of always calling
element.get("text", "")and cleaning it upfront, the optimized code first checks iftable_htmlexists. Only when falling back to text does it retrieve and process the text value, saving work in 62% of cases (214 out of 345 calls returned HTML).Conditional string conversion: The optimized code uses
isinstance(text, str)to avoid redundantstr()calls when the text is already a string, which is the common case. This eliminates double string conversions.Performance impact by test case type:
_clean_textcallsThe optimization is particularly effective because most real PDF processing workflows prioritize HTML table representations when available, making the early return path the dominant case. The inline text processing also reduces Python function call overhead, which becomes significant in data processing pipelines.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AdvancedPdfLoader._format_table_element-mhwrjz00and push.