Skip to content

[Analyzer Proposal]: Span parameter that could be a ReadOnlySpan parameter #96587

@stephentoub

Description

@stephentoub

If a Span<T> parameter is never written to by a method body, it's better for the parameter to be a ReadOnlySpan<T> rather than Span<T>. Doing so:

  • Prevents inadvertent mistakes by preventing the method from erroneously writing to the memory (short of using unsafe code)
  • Advertizes to the caller the semantics of the callee (that it won't be mutating the argument)
  • Can have better performance for the caller, e.g. if the caller has an array of reference types, constructing a ReadOnlySpan<T> is cheaper than constructing a Span<T>, as the latter needs to perform a variance check and the former does not.

We could extend such an analyzer to locals as well. This can also handle {ReadOnly}Memory.

And we should probably allow it to be configurable around visibility, e.g. default to only applying to internal/private members but allow it to be applied to public, too.

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Memorycode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixerhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions