Skip to content

[Proposal] Use Span-based methods to split strings in analyzers#54121

Open
Alex-Sob wants to merge 4 commits intodotnet:mainfrom
Alex-Sob:dev/alex-sob/span-based-split
Open

[Proposal] Use Span-based methods to split strings in analyzers#54121
Alex-Sob wants to merge 4 commits intodotnet:mainfrom
Alex-Sob:dev/alex-sob/span-based-split

Conversation

@Alex-Sob
Copy link
Copy Markdown

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?

Changes

  • Added SpanExtensions static class with these methods as simplified versions of MemoryExtensions.Split:

    public static SpanSplitEnumerator Split(this ReadOnlySpan<char> source, char separator, StringSplitOptions options = StringSplitOptions.None);
    public static SpanSplitEnumerator Split(this ReadOnlySpan<char> source, ReadOnlySpan<char> separator, StringSplitOptions options = StringSplitOptions.None);
    
    public static int Split(this ReadOnlySpan<char> source, Span<Range> destination, char separator, StringSplitOptions options = StringSplitOptions.None);
    public static int Split(this ReadOnlySpan<char> source, Span<Range> destination, ReadOnlySpan<char> separator, StringSplitOptions options = StringSplitOptions.None);
  • Replaced string.Split calls in a few places with one of the methods above. This should not only avoid allocating string[] array in each case, but this also allows to reduce allocations further, for example, if it's needed to call Trim on string parts or slice those parts. So that parts can be "materialized" into a string only if it's necessary, e.g. to pass to an API that takes a string.

    I'm replacing one more call in Reduce allocations in EnumsShouldHaveZeroValueAnalyzer #50411

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