1024programmer Asp.Net Write high-performance C# code – Span

Write high-performance C# code – Span

Write high-performance C# code – Span

Span provides a type-safe and memory-safe representation of a contiguous region of arbitrary memory. It is a ref structure allocated on the stack rather than the managed heap, and is an abstraction of an arbitrary block of memory.

1. About Span

  • First introduced in NET Core 2.1

  • Provides reading and writing of any contiguous area of ​​memoryView

  • Use indexing/iteration to modify memory in a range
  • Almost no overhead

2. Relationship with memory

Span representsa contiguous area of ​​any memory. Span instances are usually used to save elements of arrays or parts of arrays. However, unlike arrays, Span instances can point to managed memory on the stack, native memory, or managed memory.

3. Performance test

Span is usually used to process arrays, so the scenario for this test Is the splitting of an array: Starting from the middle element of an array, obtain and return one quarter of the elements.

 3.1 Array initialization

 Here we prepare an array to be initialized with three different lengths, which will help cover more test situations.

 3.2 Three methods are used for testing, Compare BenchmarkDotNet:

The first type (regular):

The second type (copy):

The third type (Span slice):

 The performance test results are as follows, you can see Span is very fast and does not occupy memory.

4. Slicing

The Span.Slice() method is to slice the memory. The third method is different from the first two. In essence, it does not create and destroy objects. It can be considered to achieve 0 memory allocation

5. ReadOnlySpan

ReadOnlySpan is a read-only representation of Span, usually used in string slicing (because of the immutability of string)

6. SpanLimitations

  1. Span is a value type that can only survive on the stack

  2. Span cannot be a field of non-stack type

  3. Span cannot be boxed

  4. Span cannot be a parameter or local variable of an asynchronous method

  5. Span cannot be captured by lambda expression

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/811377

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top