Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Stream: Byte[] vs Memory<Byte> vs Span<Byte>

Tags:

c#

.net

.net-core

What are the fundamental differences between:

var buffer = new byte[8192];
var bytesRead = Stream.Read(buffer, 0, buffer.Length);
var buffer = new byte[8192];
var span = new Span<byte>(buffer);
var bytesRead = Stream.Read(span);
var buffer = new byte[8192];
var memory = new Memory<byte>(buffer);
var bytesRead = Stream.ReadAsync(memory).Result;

Excluding the obvious fact that they are all different object types and that the only Stream.Read() method that accepts a Memory<Byte> is ReadAsync() of course.

Why would I pick any of byte[], Span<byte> or Memory<byte> over the others and how would I decide what is best for my situation?

like image 610
cogumel0 Avatar asked Dec 09 '25 15:12

cogumel0


1 Answers

Assuming this question is about Memory/Span/array and not Read/ReadAsync, there is no fundamental difference in this example.

The difference is that Memory/Span is an abstraction of memory, kind of like a safe pointer. They may represent a regular c# array, but might as well represent unmanaged memory. They might also represent memory of another type. So if some code loads data into a byte-array you can convert it to a int-array without doing a bunch of copying. It also supports slicing if you do not want the method to have access to all of the data.

The difference between Memory and Span is mostly that Span is more efficient, but has some restrictions in how it can be used.

So use whatever fits the data you have. If you are designing an API it is usually a good idea to take the most general type, i.e. Span/ReadonlySpan, and perhaps add overloads or extension methods for convenience.

like image 194
JonasH Avatar answered Dec 11 '25 05:12

JonasH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!