Best practice to allocate this byte array for this situation?

  • Thread starter Thread starter trevor.farchild
  • Start date Start date
T

trevor.farchild

Hi, long time reader, first time poster

I have an application that will be doing this 5 times a second:
Get a bunch of data from a NetworkStream and convert it into a Bitmap

Therefore, the process looks like:
Read the NetworkStream to find out size of the data
Allocate that amount as a byte array
Read the NetworkStream into the byte array
Put the byte array into a MemoryStream
Put the MemoryStream into a Bitmap

This is a tedious process and I was wondering if there was a way to
shortcut this. I tried putting a NetworkStream directly into a Bitmap
with no avail. Something to do with the NetworkStream not being
seekable.

Now, if there is no easy way to shortcut this, what's faster:
allocating a fixed amount of memory (10MB) and increase the size of
needed? Or to allocate the byte array each time. Keep in mind this
happens 5 times per second so I don't know how fast C# is at memory
management, or how it does it.
 
Hi, long time reader, first time poster

I have an application that will be doing this 5 times a second:
Get a bunch of data from a NetworkStream and convert it into a Bitmap

Therefore, the process looks like:
Read the NetworkStream to find out size of the data
Allocate that amount as a byte array
Read the NetworkStream into the byte array
Put the byte array into a MemoryStream
Put the MemoryStream into a Bitmap

This is a tedious process and I was wondering if there was a way to
shortcut this. I tried putting a NetworkStream directly into a Bitmap
with no avail. Something to do with the NetworkStream not being
seekable.

Now, if there is no easy way to shortcut this, what's faster:
allocating a fixed amount of memory (10MB) and increase the size of
needed? Or to allocate the byte array each time. Keep in mind this
happens 5 times per second so I don't know how fast C# is at memory
management, or how it does it.

5 times a second is not much - allocation take only a few microseconds on a
typical modern PC. That said, you'll get the best performance by making a
single large-enough allocation and re-using it time and again. You'll also
avoid fragmenting the GC heap and causing excess collection cycles by
holding onto a single large memory allocations.

-cd
 
Back
Top