Skip to content

Commit 5b6b476

Browse files
authored
perf(tracer): improve performance of DefaultContextProvider (#14920)
## Description Two small tweaks to improve the overhead of DefaultContextProvider. - Replace `isinstance(item, Span) with `type(item) is Span` - Skip the `isinstance` check because we should only ever have this exact class and not a subclass - Remove calls to `Span.finished` which is a computed property ## Testing <!-- Describe your testing strategy or note what tests are included --> ## Risks <!-- Note any risks associated with this change, or "None" if no risks --> ## Additional Notes <!-- Any other information that would be helpful for reviewers -->
1 parent b599d88 commit 5b6b476

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

ddtrace/_trace/provider.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ def activate(self, ctx: Optional[ActiveTrace]) -> None:
7171
def active(self) -> Optional[ActiveTrace]:
7272
"""Returns the active span or context for the current execution."""
7373
item = _DD_CONTEXTVAR.get()
74-
if isinstance(item, Span):
74+
75+
# PERF: type(item) is Span is about the same perf as isinstance(item, Span)
76+
# when item is a Span, but slower when item is a Context
77+
if type(item) is Span:
7578
return self._update_active(item)
7679
return item
7780

@@ -82,8 +85,9 @@ def _update_active(self, span: Span) -> Optional[ActiveTrace]:
8285
If no parent exists and the context is reactivatable, that context is restored.
8386
"""
8487
new_active: Optional[Span] = span
85-
# PERF: Avoid calling `Span.finished` more than once per span. This is a computed property.
86-
while new_active and new_active.finished:
88+
# PERF: Avoid checking if the span is finished more than once per span.
89+
# PERF: By-pass Span.finished which is a computed property to avoid the function call overhead
90+
while new_active and new_active.duration_ns is not None:
8791
if new_active._parent is None and new_active._parent_context and new_active._parent_context._reactivate:
8892
self.activate(new_active._parent_context)
8993
return new_active._parent_context

0 commit comments

Comments
 (0)