如何从 .NET 中的内存映射文件快速读取字节?
在某些情况下,MemoryMappedViewAccessor
类并不能有效地读取字节;我们得到的最好的是通用的ReadArray
,它是所有结构的路由,并且当您只需要字节时涉及几个不必要的步骤。
可以使用MemoryMappedViewStream
,但因为它基于Stream
,所以您需要首先寻找正确的位置,然后读取操作本身有更多不必要的步骤。
考虑到它应该只是要读取的地址空间的特定区域,是否有一种快速、高性能的方法可以从 .NET 中的内存映射文件中读取字节数组?
In some situations the MemoryMappedViewAccessor
class just doesn't cut it for reading bytes efficiently; the best we get is the generic ReadArray<byte>
which it the route for all structs and involves several unnecessary steps when you just need bytes.
It's possible to use a MemoryMappedViewStream
, but because it's based on a Stream
you need to seek to the correct position first, and then the read operation itself has many more unnecessary steps.
Is there a quick, high-performance way to read an array of bytes from a memory-mapped file in .NET, given that it should just be a particular area of the address space to read from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该解决方案需要不安全的代码(使用
/unsafe
开关编译),但直接获取指向内存的指针;然后可以使用Marshal.Copy。这比 .NET 框架提供的方法快得多。This solution requires unsafe code (compile with
/unsafe
switch), but grabs a pointer to the memory directly; thenMarshal.Copy
can be used. This is much, much faster than the methods provided by the .NET framework.我知道这是一个较旧的问题,已得到解答,但我想补充我的两分钱。
我使用已接受的答案(使用不安全代码)和 MemoryMappedViewStream 方法进行了测试,以读取 200MB 字节数组。
MemoryMappedViewStream
我对每种方法运行了 3 次测试,并收到了以下次数。
MemoryMappedViewStream:
不安全方法
从少量测试来看,
MemoryMappedViewStream
具有非常轻微的优势。考虑到这一点,对于任何阅读这篇文章的人来说,我都会选择MemoryMappedViewStream
。I know this is an older question which has been answered but I wanted to add my two cents.
I ran a test with both the accepted answer (using the unsafe code) and with the MemoryMappedViewStream approach for reading a 200MB byte array.
MemoryMappedViewStream
I ran the test 3 times with each approach and received the following times.
MemoryMappedViewStream:
Unsafe method
From the small amount of testing it looks like the
MemoryMappedViewStream
has a very slight advantage. With that in mind for anyone reading this post down the road I would go with theMemoryMappedViewStream
.请参阅此错误报告:无法确定 MemoryMappedViewAccessor 使用的内部偏移量 - 使得SafeMemoryMappedViewHandle 属性不可用。
从报告中:
See this bug report: No way to determine internal offset used by MemoryMappedViewAccessor - Makes SafeMemoryMappedViewHandle property unusable.
From the report:
这个解决方案的一个安全版本是:
我已经测试过这个,它确实有效。我无法评论它的性能,也无法评论它是否是最好的整体解决方案。
A safe version of this solution is:
I have tested this, it does work. I cannot comment on it's performance or if it's the BEST overall solution just that it works.
只是想与 long l_offset 共享一个版本(因此可以读取\写入大于 int32 最大大小的文件):
Just wanted to share a version with long l_offset (so it is possible to read\write files larger than int32 max size):