Skip to content

Detect when copying Range-based indexers are being used with a Span or Memory target. #33829

@bartonjs

Description

@bartonjs

The decision for Range based indexers is they return the type they're declared on:

var val = str[x..y];

Produces a string, the same as str.Substring(x, y-x). Due to implicit conversions, this simple-looking statement is actually a copy:

ReadOnlySpan<char> val = str[x..y];

Since strings are immutable, this pattern should almost always be an error, and replaced with a call to AsSpan:

ReadOnlySpan<char> val = str.AsSpan(x, y-x);

For arrays, and any other sources, it's possible that a copy was actually desired... but it's probably not the majority case. Since it's less slam-dunk it might warrant a different diagnostic ID so it can be suppressed differently than the string variant.

Fixer: Replace range indexer use with calls to AsSpan or AsMemory. (If actual Index types were used the fix is more complicated, since it requires calling GetOffsetAndLength and using temporary variables, while maintaining order of evaluation).

Category: Performance

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-Metacode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions