⚡️ Speed up function build_otel_context by 16%
#162
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.
📄 16% (0.16x) speedup for
build_otel_contextinmlflow/tracing/utils/__init__.py⏱️ Runtime :
1.81 milliseconds→1.56 milliseconds(best of66runs)📝 Explanation and details
The optimization replaces keyword arguments with positional arguments when calling
trace_api.SpanContext(), achieving a 15% speedup.Key Change:
trace_api.SpanContext(trace_id=trace_id, span_id=span_id, is_remote=False)trace_api.SpanContext(trace_id, span_id, False)Why This is Faster:
In Python, keyword arguments require dictionary lookups and additional processing overhead. Positional arguments are passed directly to the function, avoiding the parameter name resolution step. The line profiler shows the original version spent significant time on individual parameter assignments (8%, 6.6%, and 7% of total time), while the optimized version eliminates this overhead entirely.
Performance Impact:
Based on the function references,
build_otel_contextis called frequently in MLflow's span deserialization pipeline - specifically inSpan.from_dict(),Span.from_dict_v2(), andSpan.from_otel_proto()methods. These methods are used when reconstructing span objects from stored data or network protocols, making this a hot path optimization.Test Case Performance:
The annotated tests show consistent 15-25% improvements across all scenarios:
This optimization is particularly effective for high-throughput tracing workloads where spans are frequently deserialized, as the cumulative effect of the 15% improvement per call becomes significant.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-build_otel_context-mhwxwtvqand push.