What is more fasten, AsSpan or Substring in C#?

What is more fasten, AsSpan or Substring in C#?

In general, AsSpan is faster than Substring in C#. This is because AsSpan returns a span (a lightweight structure that represents a contiguous region of memory) that refers to a portion of the original string, whereas Substring creates a new string object that contains a copy of the specified portion of the original string. Since creating and copying a new string object requires more memory allocation and manipulation, it is generally slower than using a span to refer to an existing region of memory.

Here is an example that compares the performance of AsSpan and Substring:

string s = "Hello, world!";

// Use AsSpan to get a span that refers to the first 7 characters of the string
ReadOnlySpan<char> span = s.AsSpan(0, 7);

// Use Substring to create a new string that contains the first 7 characters of the original string
string substring = s.Substring(0, 7);

// Measure the performance of using AsSpan and Substring
var stopwatch = new Stopwatch();
stopwatch.Start();

for (int i = 0; i < 10000000; i++)
{
    span.ToString();
}

stopwatch.Stop();

Console.WriteLine($"Using AsSpan: {stopwatch.ElapsedMilliseconds}ms");

stopwatch.Restart();

for (int i = 0; i < 10000000; i++)
{
    substring.ToString();
}

stopwatch.Stop();

Console.WriteLine($"Using Substring: {stopwatch.ElapsedMilliseconds}ms");

This code measures the time it takes to convert a span or substring to a string 10 million times. As expected, using AsSpan is faster than using Substring. However, the difference in performance may not be significant in many cases, and the appropriate method to use will depend on your specific use case and requirements.