Use ref and Span & lt; T & gt; In. Net Core to improve program performance.

Source: Internet
Author: User

. Net Core uses ref and Span <T> to improve program performance.

I. Preface

Actually, when it comes to ref, many people already know it. ref is a language feature of C #7.0. It provides developers with a mechanism to return local variable references and value references.
Span is also a complex data type based on the ref syntax. In the second half of the article, I will give an example to illustrate how to use it.

Ii. ref keywords

Whether it is ref or out, it is a language feature that is difficult to understand and operate. For example, in C language, such advanced syntax always has some side effects, but I don't think there is anything, and not every C # developer must have a deep understanding of these internal running mechanisms, I think no matter what complicated things are just a free choice for people, risks and flexibility will never be compatible.

Let's look at several examples to illustrate the similarities between references and pointers. Of course, the following method can be used as early as C #7.0:

public static void IncrementByRef(ref int x){ x++;}public unsafe static void IncrementByPointer(int* x){ (*x)++;}

The above two functions use ref and non-secure pointers to complete parameter + 1.

int i = 30;IncrementByRef(ref i);// i = 31unsafe{ IncrementByPointer(&i);}// i = 32

The following are the features provided by C #7.0:

1. ref locals (reference local variables)

int i = 42;ref var x = ref i;x = x + 1;// i = 43

In this example, x is referenced by the local I variable. When the value of x is changed, the value of the I variable is also changed.

2. ref returns (return value reference)

Ref returns is a powerful feature in C #7. The following code best reflects its features. This function provides a reference to return a reference to an int array:

public static ref int GetArrayRef(int[] items, int index) => ref items[index];

Obtain the reference of the project in the array by subscript. When the reference value is changed, the array also changes.

Iii. Span

System. Span is a part of the Core of. Net Core, which is under the System. Memory. dll assembly. This feature is currently independent and may be integrated into CoreFx in the future;

How to use it? REFERENCE The following NuGet package under the project created by. Net Core 2.0 SDK:

 <ItemGroup> <PackageReference Include="System.Memory" Version="4.4.0-preview1-25305-02" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.4.0-preview1-25305-02" /> </ItemGroup>

We can see the single-value object operation method similar to pointer (T *) that can be provided using the ref keyword. Basically, the Operation pointer in the. NET system is not considered a good event. Of course,. NET provides us with a ref for safe operation single value reference. However, a single value is only a small part of the user's need to use the "Pointer". For pointers, it is more common to operate on a series of continuous "elements" in the memory space.

Span indicates a continuous memory block of known length and type. In many aspects, it is very similar to T [] or ArraySegment. It provides safe access to the memory area pointer. In fact, I understand that it will be the abstraction of the void * pointer in. NET, and developers familiar with C/C ++ should better understand what this means.

Span has the following features:

• Abstracts all types of continuous memory space systems, including: arrays, unmanaged pointers, stack pointers, fixed or pinned hosted data, and reference of value internal areas
• Supports CLR Standard Object Types and value types
• Supports generic
• Supports GC, instead of managing release by yourself as a pointer

Next, let's take a look at the definition of Span. It has a syntactic and semantic relationship with ref:

public struct Span<T> { ref T _reference; int _length; public ref T this[int index] { get {...} } ...}public struct ReadOnlySpan<T> { ref T _reference; int _length; public T this[int index] { get {...} } ...}

Next, I will use an intuitive example to illustrate the use scenario of Span. Let's take the case of character truncation and character conversion (converted to an integer:

If there is a stringstring content = "content-length:123",To convert 123 to an integer type, Substring is used to truncate a string unrelated to a number. The conversion code is as follows:

string content = "content-length:123";Stopwatch watch1 = new Stopwatch();watch1.Start();for (int j = 0; j < 100000; j++){ int.Parse(content.Substring(15));}watch1.Stop();Console.WriteLine("\tTime Elapsed:\t" + watch1.ElapsedMilliseconds.ToString("N0") + "ms");

Why is this example used? This is a typical use case of substring. Each string operation generates a new string object, not just a Substring, but an int. when Parse is used, the string object is repeatedly operated. If a large number of operations are performed, the GC is put under pressure.

Use Span to implement this algorithm:

string content = "content-length:123";ReadOnlySpan<char> span = content.ToCharArray(); span.Slice(15).ParseToInt();watch.Start();for (int j = 0; j < 100000; j++){ int icb = span.Slice(15).ParseToInt();}watch.Stop();Console.WriteLine("\tTime Elapsed:\t" + watch.ElapsedMilliseconds.ToString("N0") + "ms");

Here, the string-to-int algorithm is implemented using ReadonlySpan, which is also a typical use case of Span. The official scenario is also as follows. Span is applicable to scenarios where continuous memory is reused for multiple times.

The conversion code is as follows:

public static class ReadonlySpanxtension{ public static int ParseToInt(this ReadOnlySpan<char> rspan) {  Int16 sign = 1;  int num = 0;  UInt16 index = 0;  if (rspan[0].Equals('-')){   sign = -1; index = 1;  }  for (int idx = index; idx < rspan.Length; idx++){   char c = rspan[idx];   num = (c - '0') + num * 10;  }  return num * sign; }}

Iv. Final

The time for 100000 calls to the above two code segments is as follows:

String Substring Convert:  Time Elapsed: 18msReadOnlySpan Convert:  Time Elapsed: 4ms

Currently, there is enough support for Span, which is only the most basic architecture. Later, CoreFx will refactor and implement many APIs using Span. It can be seen that the performance of. Net Core will become more and more powerful in the future.

The above is a small series for you to introduce.. Net Core uses ref and Span <T> to improve program performance. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.