Best practice to allocate this byte array for this situation?

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

Carl Daniel [VC++ MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top