2

I have an array of some type (short[], int[], or similar base type). I want to send it through a stream, so I need it to be byte[]. The standard solution seems to be creating a new byte[] array, and use BitConverter. The problem with this approach is performance and memory usage - it requires allocating all new memory, copying into the new memory, and then writing the byte[] to the stream.

I very much want to use the original backing memory of the int[] array as a byte[] array so I can send it in-place. I am willing to enforce the requirement that the sending and receiving system must be the same endianness, for the sake of this very obvious and very significant performance difference.

Is there some way to treat an array of int[] or similar, as a byte[] in-place?

2
  • stackoverflow.com/a/66983061 Commented Dec 5, 2021 at 15:49
  • If Span<T> isn't available, remember that if you are writing to a stream, you don't have to convert the entire array at once, you can do it chunk by chunk. It won't save you processing cycles but it won't cost you much in memory Commented Dec 5, 2021 at 16:08

1 Answer 1

5

If you can use Span<T> (.net core 3+):

void Send(int[] data)
{
    ReadOnlySpan<byte> byteRef = MemoryMarshal.AsBytes(data.AsSpan());
    _stream.Write(byteRef);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is great news, thanks for the reply! I am now reading up on Span<T> and I will need to figure out how to convert back, at the receiver end, from byte[] to int[]. If you happen to post that before I find it, it would be appreciated.
On the receiving end, simply create another int[], and a Span<byte> from it, and _stream.Read() into the span. Easy peasy. :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.