⚡️ Speed up method BatchReference._to_internal by 185%
#106
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.
📄 185% (1.85x) speedup for
BatchReference._to_internalinweaviate/collections/classes/batch.py⏱️ Runtime :
2.35 milliseconds→825 microseconds(best of162runs)📝 Explanation and details
The optimized code achieves a 185% speedup by eliminating three key performance bottlenecks:
What was optimized:
Eliminated object mutation: The original code modified
self.to_object_collectiondirectly, which is expensive in Pydantic models due to validation overhead. The optimization uses a local variabletoc_strinstead, avoiding the mutation entirely.Cached UUID string conversions: The original code called
str(self.from_object_uuid)andstr(self.to_object_uuid)multiple times. The optimization computes these once and reuses the cached strings, eliminating redundant conversions.Optimized string concatenation: Replaced the slower
self.to_object_collection + "/"concatenation with f-string formattingf"{toc}/", which is more efficient in Python.Why this leads to speedup:
Performance characteristics:
The optimization shows consistent 180-240% speedups across all test scenarios, with particularly strong performance on:
The optimization maintains identical behavior and output while dramatically improving performance for any workload involving batch reference creation.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-BatchReference._to_internal-mh38jgyiand push.