-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
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