Skip to content

CA1846: Prefer AsSpan over Substring #10299

@himgoyalmicro

Description

@himgoyalmicro

Link to issue description: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1846

Rule Description:

Substring allocates a new string object on the heap and performs a full copy of the extracted text. String manipulation is a performance bottleneck for many programs. Allocating many small, short-lived strings on a hot path can create enough collection pressure to impact performance. The O(n) copies created by Substring become relevant when the substrings get large. The Span and ReadOnlySpan types were created to solve these performance problems.

Many APIs that accept strings also have overloads that accept a ReadOnlySpan<System.Char> argument. When such overloads are available, you can improve performance by calling AsSpan instead of Substring.

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions