Memory optimisation for GetLastActiveSpan #2633
Closed
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.
#skip-changelog
Overview
When load testing an ASP.NET Core application that creates a lot of spans,
GetLastActiveSpanwas responsible for a significant proportion of memory allocation:This appears to be due to the call to
Spans.OrderByDescending:sentry-dotnet/src/Sentry/TransactionTracer.cs
Line 381 in bbe4fa9
Iteration 1
By replacing this with a for loop, memory consumption in our benchmark dropped by 65.68% from 2109.85 KB to 724.02 KB
Before
After
Iteration 2
By instead keeping all the spans on a Stack and inspecting the most recent one(s) to return the last active span when required we were able to reduce memory usage for the 100 spans scenario drops by a further 63.25% from 724.02 KB to 266.09 KB. So about an ~87% reduction vs the original benchmarks.
After