Span< T>和记忆T在C#7.2中? [英] What is the difference between Span<T> and Memory<T> in C# 7.2?

查看:91
本文介绍了Span< T>和记忆T在C#7.2中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#7.2引入了两种新类型:Span<T>Memory<T>,它们比早期的C#类型(如string[])具有更好的性能.

C# 7.2 introduces two new types: Span<T> and Memory<T> that have better performance over earlier C# types like string[].

问题:Span<T>Memory<T>有什么区别?为什么我要在另一个上使用?

Question: What is the difference between Span<T> and Memory<T>? Why would I use one over the other?

推荐答案

Span<T>本质上是仅堆栈的,而Memory<T>可以存在于堆中.

Span<T> is stack-only in nature while Memory<T> can exist on the heap.

Span<T>是我们要添加到平台中以表示的新类型 具有性能的任意内存的连续区域 特性与T []相当.其API与数组相似, 但是与数组不同,它可以指向托管或本机内存,或者 到在堆栈上分配的内存.

Span<T> is a new type we are adding to the platform to represent contiguous regions of arbitrary memory, with performance characteristics on par with T[]. Its APIs are similar to the array, but unlike arrays, it can point to either managed or native memory, or to memory allocated on the stack.

Memory <T>是对Span<T>进行补充的类型.正如其设计中所讨论的 在文档中,Span<T>是仅堆栈类型.的仅堆栈性质 Span<T>使其不适用于需要存储的许多情况 引用堆上的缓冲区(用Span<T>表示),例如为了 进行异步调用的例程.

Memory <T> is a type complementing Span<T>. As discussed in its design document, Span<T> is a stack-only type. The stack-only nature of Span<T> makes it unsuitable for many scenarios that require storing references to buffers (represented with Span<T>) on the heap, e.g. for routines doing asynchronous calls.

async Task DoSomethingAsync(Span<byte> buffer) {
    buffer[0] = 0;
    await Something(); // Oops! The stack unwinds here, but the buffer below
                       // cannot survive the continuation.
    buffer[0] = 1;
}

为解决此问题,我们将提供一组互补类型, 旨在用作代表以下目的的通用交换类型: 就像Span <T>一样,是任意范围的内存,但与Span <T>不同 这些类型将不是仅堆栈式的,代价是 读写内存的性能损失.

To address this problem, we will provide a set of complementary types, intended to be used as general purpose exchange types representing, just like Span <T>, a range of arbitrary memory, but unlike Span <T> these types will not be stack-only, at the cost of significant performance penalties for reading and writing to the memory.

async Task DoSomethingAsync(Memory<byte> buffer) {
    buffer.Span[0] = 0;
    await Something(); // The stack unwinds here, but it's OK as Memory<T> is
                       // just like any other type.
    buffer.Span[0] = 1;
}

在上面的示例中,Memory <byte>用于表示缓冲区. 它是常规类型,可以在进行异步的方法中使用 电话.其Span属性返回Span<byte>,但返回值 不会在异步调用期间存储在堆中,而是 从Memory<T>值产生新值.从某种意义上说 Memory<T>Span<T>的工厂.

In the sample above, the Memory <byte> is used to represent the buffer. It is a regular type and can be used in methods doing asynchronous calls. Its Span property returns Span<byte>, but the returned value does not get stored on the heap during asynchronous calls, but rather new values are produced from the Memory<T> value. In a sense, Memory<T> is a factory of Span<T>.

参考文档:此处

这篇关于Span&lt; T&gt;和记忆T在C#7.2中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆