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?
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.
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.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
.