是否存在接受Span T的MemoryStream?或记忆T? [英] Is there a MemoryStream that accepts a Span<T> or Memory<T>?

查看:38
本文介绍了是否存在接受Span T的MemoryStream?或记忆T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从许多来源(MemoryMappedFiles或FileStream)读取数据.一个问题是,每次读取字节,int或其他某种类型的调用都非常慢.因此,我想将大块数据读取到一个数组中,并将其移交给轻量级的内存流,并在那里读取单个组件.

I'm reading data from many sources (MemoryMappedFiles or FileStream). One problem is though that every single call to read a byte, int or some other type is extremely slow. So I'd like to read a chunk of data into an array and hand this over to a lightweight memory stream and do the reading of the individual components there.

问题是当前的.NET MemorySrream仅允许在构造函数中使用数组,但是我需要一个能够处理Span或Memor的Stream..Net源代码中深深地嵌入了一个ReadOnlyMemoryStream作为内部类.

The problem is that the current MemorySrream of .NET does only allow an array in the constructor, but I would need a Stream that is able to handle Span or Memor for example. There is a ReadOnlyMemoryStream as an internal class deeply buried in the .NET source code.

有趣的是,尽管ReadOnlyMemoryStream的速度比MemoryStream慢,但我认为它不会产生太大的变化.

The interesting thing is though that the ReadOnlyMemoryStream is slower than the MemoryStream where I would have thought it shouldn't make a big difference.

有没有更好的实现方法?

Is there any better implementation?

推荐答案

如果您有一个 Span ,则已经达到了它的最快速度,只需直接阅读即可,而不必放入流中在它上面.

If you have a Span, you're already as fast as it gets, just read straight through it instead of plopping a stream on top of it.

Span 甚至可以让您访问真正漂亮的东西,例如直接的 struct 映射而不复制( MemoryMarshal.Cast ),跨度增量(相当于流前进,是 Unsafe.Add 的一部分),如果实际需要则阻止复制( Unsafe.Copy )等.

A Span even gives you access to really nifty things like straight struct mapping without copies (MemoryMarshal.Cast), span increments (the equivalent to a stream advancing, part of Unsafe.Add), block copies if actually necessary (Unsafe.Copy) etc.

这篇关于是否存在接受Span T的MemoryStream?或记忆T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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