Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

Alex-Sob
Copy link

@Alex-Sob Alex-Sob commented Aug 21, 2025

I would like to suggest PR that is reducing allocations EnumsShouldHaveZeroValueAnalyzer:

  • Currently the analyzer allocates ImmutableArray to store zero value fields of an enum type. It can be removed, in the case when there are multiple zero value fields the analyzer just needs to report an error, it can use a flag for that.

  • GetZeroValueFields method allocates two enumerators with Where and Cast calls, they can be removed.

  • When the analyzer gets zero value field names from analyzer options it allocates array for separator new[] { '|' }, string[] and multiple string parts with string.Split, ImmutableArray and also a delegate with closure. All those allocations can be removed, particularly string.Split call can be replaced with Span-based splitting.

    In .NET 8+ there are MemoryExtensions.Split methods to split strings that are Span-based, but they are unavailable for analyzers since they target netstandard2.0. What about providing some Span-based helpers that could be used in analyzers? I'm proposing to add such a helper in [Proposal] Use Span-based methods to split strings in analyzers #50581. In this PR I'm using the same helper in EnumsShouldHaveZeroValueAnalyzer.

@Alex-Sob Alex-Sob requested a review from a team as a code owner August 21, 2025 17:12

internal static class SpanExtensions
{
public static SpanSplitEnumerator Split(this ReadOnlySpan<char> source, char separator)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stephentoub There are new MemoryExtensions.Split<T> methods introduced in .NET 9, but they are unavailable for analyzers since they target netstandard2.0. Do you think it's ok to provide a simplified version to be used for analyzers? For example, it could be used in EnumsShouldHaveZeroValueAnalyzer and considerably reduce allocations. By the way, it seems that Range and Index here are local versions of respective BCL types.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like there's no test project for Analyzer.Utilities projects, so I'm not sure where to add unit tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants