The introduction

C# is a modern programming language, very similar to Java. Skilled developers can even switch seamlessly to Java in three days. Ecological performance is also flourishing everywhere. Today, let’s take a look at span-related performance optimization in C#

What is the Span

System.span is a new value type that plays a key role in.NET. You can use it to represent contiguous regions of any memory, whether the corresponding memory is associated with managed objects, provided by native code through interoperability, or located on the stack. In addition to the above purposes, it still ensures secure access and high performance features, just like arrays.

Span is a value type. Its value is that it allows us to store any type in an adjacent area. This includes:

  • Unmanaged memory
  • The stack
  • Managed memory

A performance improvement for String

Some websites usually publish the list of winners (DOGE) after finishing the activities. Now the demand is that we want to code the middle few words of the user name, for example, “Lin Shen deer”, we want to write it as “Lin * deer” to protect user privacy.

Look at some code:

Let’s concatenate the string with the parameter “program girl” and see the output:

Very nice, very easy

Next, let’s use the Span implementation:

static void Main(string[] args)
{
    Console.WriteLine(ObfuscatePhoneSpan("The program girl."));
}

static string ObfuscatePhoneSpan(string id)
{
    return string.Create(id.Length, id, (sc, value) = > {int n = id.Length / 2;
        int r = id.Length - (id.Length * 20 / 100) - n; // Number of replacements = (total) - (20%) - (half)

        value.AsSpan().CopyTo(sc);
        sc.Slice(n, r).Fill(The '*');
    });
}
Copy the code

The value variable is a string, and it provides the AsSpan method, which gives us an instance of Span, and finally cuts r characters from n through the Slice method and fills them with *

The test code

Final performance comparison

Write in the last

The above code Span exceeds the array of apis provided by the string native API Span in both memory footprint and average time, allowing us to use native code in C#, giving us much better performance.