Using ref and span<t> to improve program performance in. NET Core

Source: Internet
Author: User

First, preface

In fact, when it comes to ref, a lot of students know about it, ref is a language feature of C # 7.0, which provides a mechanism for developers to return local variable references and value references.

Span is also a complex data type based on the ref syntax, and in the latter part of the article, there is an example of how to use it.

Second, ref keyword

Either the ref or the Out keyword is a language feature that is more difficult to understand and manipulate, such as manipulating pointers in C. This high-level syntax always brings some side effects, but I don't think there's anything, and not every C # developer has a deep understanding of these internal operating mechanisms, and I feel that whatever complex thing is just a free choice for people, risk and flexibility will never be taken into account.

Here are a few examples of how the reference and pointer are the same, and of course the following usage is available before C # 7.0:

 Public Static void Incrementbyref (refint  x) {    x+ +;}  Public unsafe Static void Incrementbypointer (int* x) {   (*x) + +;}

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

int  - ; Incrementbyref (ref i); // i = unsafe {   incrementbypointer (&i);} // i =

The following are the features that C # 7.0 provides:

  1. Ref locals (referencing local variables)

int  the ; ref var ref  1; // i =

In this example, a reference to the local I variable is x, and the value of the I variable changes when the value of x is changed.

2. Ref returns (return value reference)

Ref returns is a powerful feature in C # 7, and the following code is the best embodiment of its characteristics, which provides a reference to an item in an int array:

 Public Static ref int Getarrayref (intintref Items[index];

When you change the reference value by using the subscript to obtain a reference to the items in the array, the array changes as well.

Three, Span

System.span is part of the. Net core Core, under the System.Memory.dll assembly. Currently this feature is independent and may be integrated into the COREFX in the future;

How to use it? The following NuGet packages are referenced under the project created by the. Net Core 2.0 SDK:

<ItemGroup>    <packagereferenceInclude= "System.memory"Version= "4.4.0-preview1-25305-02" />    <packagereferenceInclude= "System.Runtime.CompilerServices.Unsafe"Version= "4.4.0-preview1-25305-02" /></ItemGroup>

In the above we see the way of manipulating a single value object using a pointer (t*) that can be supplied with the REF keyword. Basically in. NET system operation pointers are not considered a good event, of course. NET provides us with a safe operation of a single value reference to ref. But a single value is just a small part of the user's need for a "pointer"; for pointers, it is more common to manipulate "elements" in a series of contiguous memory spaces.

Span is expressed as a contiguous block of memory of a known length and type. In many ways it is very similar to t[] or arraysegment, which provides the ability to access the memory area pointers securely. Actually, I understand it. NET operation (void*) pointer abstraction, familiarity with C + + developers should be more aware of what this means.

The features of span are as follows:

1) A type system that abstracts all contiguous memory spaces, including: arrays, unmanaged pointers, stack pointers, fixed or pinned managed data, and references to values inside areas;

2) supports CLR standard object types and value types;

3) support generic type;

4) Support GC, rather than the pointer need to manage the release itself;

Here's a definition of span, which has a syntactic and semantic connection to ref:

 Public structSpan<t> {      refT _reference; int_length;  Public refT This[intIndex] {Get {...} } ...} Public structReadonlyspan<t> {      refT _reference; int_length;  PublicT This[intIndex] {Get {...} } ...}

Next, we use a visual example to illustrate the usage scenario of span, with the example of character interception and character conversion (converting to Integer):

If there is a string content = "content-length:123", to convert 123 to an integer, it is common practice to truncate the string that is independent of the numeric character, and the conversion code is as follows: substring

stringContent ="content-length:123"; Stopwatch Watch1=NewStopwatch (); Watch1. Start (); for(intj =0; J <100000; J + +){        int. Parse (content. Substring ( the));} Watch1. Stop (); Console.WriteLine ("\ttime elapsed:\t"+ Watch1. Elapsedmilliseconds.tostring ("N0") +"Ms");

Why use this example, this is a typical substring usage scenario where a string is generated each time a new string object is created, of course, not just substring, in Int. Parse when the string object is repeated, if a large number of operations will put pressure on the GC.

Use span to implement this algorithm:

stringContent ="content-length:123"; Readonlyspan<Char> span =content.    ToCharArray (); Span. Slice ( the). Parsetoint (); watch. Start (); for(intj =0; J <100000; J + +){        intICB = span. Slice ( the). Parsetoint ();} Watch. Stop (); Console.WriteLine ("\ttime elapsed:\t"+ Watch. Elapsedmilliseconds.tostring ("N0") +"Ms");

Here the algorithm of converting string to int is implemented using Readonlyspan, which is also a typical usage scenario for spans, as is the case with the official scenario, where span is suitable for multiple multiplexed operations of contiguous memory.

The conversion code is as follows:

 Public Static classreadonlyspanxtension{ Public Static intParsetoint ( Thisreadonlyspan<Char>Rspan) {Int16 sign=1; intnum =0; UInt16 Index=0; if(rspan[0]. Equals ('-') ) { sign= -1; index =1; }               for(intIDX = index; IDX < Rspan. Length; idx++)        {                    Charc =Rspan[idx]; Num= (C-'0') + num *Ten; }
returnNum *Sign ; }}

Iv. final

The time of the above two code 100,000 calls is as follows:

String Substring convert:time Elapsed:18msreadonlyspan convert:time elapsed:4ms

The current span support is not enough, it's just the most basic architecture, and then COREFX will use span for many APIs to refactor and implement. Visible. Net core performance will become more powerful in the future.

Reference Link: http://www.cnblogs.com/maxzhang1985/p/6875622.html

Using ref and span<t> to improve program performance in. NET Core

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.