Skip to content

Commit

Permalink
Make SpanFromContext zero alloc when there is no span
Browse files Browse the repository at this point in the history
  • Loading branch information
pellared committed Mar 8, 2024
1 parent fd7e57b commit 29c90a0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
6 changes: 4 additions & 2 deletions trace/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,16 @@ func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) conte
// performs no operations is returned.
func SpanFromContext(ctx context.Context) Span {
if ctx == nil {
return noopSpan{}
return noopSpanInstance
}
if span, ok := ctx.Value(currentSpanKey).(Span); ok {
return span
}
return noopSpan{}
return noopSpanInstance
}

var noopSpanInstance Span = noopSpan{}

// SpanContextFromContext returns the current Span's SpanContext.
func SpanContextFromContext(ctx context.Context) SpanContext {
return SpanFromContext(ctx).SpanContext()
Expand Down
2 changes: 1 addition & 1 deletion trace/noop.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (t noopTracer) Start(ctx context.Context, name string, _ ...SpanStartOption
span := SpanFromContext(ctx)
if _, ok := span.(nonRecordingSpan); !ok {
// span is likely already a noopSpan, but let's be sure
span = noopSpan{}
span = noopSpanInstance
}
return ContextWithSpan(ctx, span), span
}
Expand Down

0 comments on commit 29c90a0

Please sign in to comment.