-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Avoid delegate allocation in TraceSourceLoggerProvider.GetOrAddTraceSource #71134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…ource Every call to GetOrAddTraceSource was allocating a new delegate instance.
|
Tagging subscribers to this area: @dotnet/area-extensions-logging Issue DetailsEvery call to GetOrAddTraceSource was allocating a new delegate instance.
|
danmoseley
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit, maybe long enough to have some curlies.
eerhardt
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
| _sources.TryGetValue(name, out DiagnosticsTraceSource? source) ? source : | ||
| _sources.GetOrAdd(name, InitializeTraceSource(name)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It feels like this is such a perf trap ... 99.9% of devs would write the code as it was originally.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If InitializeTraceSource was static, it'd be ok (as of C# 11 and its caching of method group delegates). But as an instance method, the compiler is forced to allocate a new delegate. That's the nature of implicit delegate conversions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The other option here is:
_sources.GetOrAdd(name, static (name, self) => self.InitializeTraceSource(name), this)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It feels like this is such a perf trap
It's been this way for a very, very long time. Since most code won't have an observable perf impact of a delegate allocation in a call like this, it hasn't been too big a deal for most of that time (IMO of course).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The other option here is
This library has a netstandard2.0 target.
Every call to GetOrAddTraceSource was allocating a new delegate instance.