Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
Reading Stream: Byte[] vs Memory<Byte> vs Span<Byte>

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda