⚡️ Speed up method OtelInterceptor.intercept_unary_unary by 49%
#23
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.
📄 49% (0.49x) speedup for
OtelInterceptor.intercept_unary_unaryinchromadb/telemetry/opentelemetry/grpc.py⏱️ Runtime :
664 microseconds→445 microseconds(best of91runs)📝 Explanation and details
The optimization achieves a 49% speedup by eliminating repeated import overhead, which was the primary performance bottleneck.
Key optimizations:
Module-level imports: Moved
tracer,_encode_span_id, and_encode_trace_idimports to the top of the file. The line profiler shows the original code spent 36.4% of execution time (895,930ns out of 2,459,270ns) on the repeatedfrom chromadb.telemetry.opentelemetry import tracerimport in every call.Reduced attribute lookups: Cached
span.get_span_context()in a local variablectxto avoid calling it twice for trace_id and span_id extraction. Also cachedresult.code()to avoid repeated method calls.Optimized metadata handling:
[:]append()calls instead ofextend()for adding the two metadata itemsThe optimization is most effective for scenarios with frequent tracer-disabled calls (46-99% speedup in tests) and high-volume call patterns (52% speedup for 500 calls), making it ideal for production environments where telemetry may be conditionally enabled and gRPC calls are frequent.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-OtelInterceptor.intercept_unary_unary-mh1tobspand push.