Skip to content

Files

Latest commit

 

History

History
35 lines (25 loc) · 1.27 KB

File metadata and controls

35 lines (25 loc) · 1.27 KB

Pattern: Use of Substring() over AsSpan()

Issue: -

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<T> and ReadOnlySpan<T> 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.

Example of incorrect code:

public void TestMethod(string iniFileLine)
{
    // Violation
    int.TryParse(iniFileLine.Substring(7), out int x);
    int.TryParse(iniFileLine.Substring(2, 5), out int y);
}

Example of correct code:

public void TestMethod(string iniFileLine)
{
    // Fix
    int.TryParse(iniFileLine.AsSpan(7), out int x);
    int.TryParse(iniFileLine.AsSpan(2, 5), out int y);
}

Further Reading