views:

27

answers:

1

I know it's subjective but this was the result I came up with based on the answer to me previous question and it seems a bit "slapped together", as I have changed it quite a bit:

  Private Function ReadFromBuffer(ByVal objReader As NetworkStream) As Byte()
    Dim intRead As Integer = 1024
    Dim allBytes(-1) As Byte

    While intRead = 1024
        Dim byteTempbuffer(1023) As Byte
        intRead = objReader.Read(byteTempbuffer, 0, 1024)
        ReDim Preserve byteTempbuffer(intRead - 1)
        Dim tempold(allBytes.Length - 1) As Byte
        tempold = allBytes
        allBytes = tempold.Concat(byteTempbuffer).ToArray
    End While

    Return allBytes
End Function

Basically is there a better way to write this (even just part of the code) or a more efficient way to do it?

Basically the code is there to read all the bytes from a networkstream 1024 bytes at a time. And each time it reads the bytes it puts into one array which is returned.

The thing i think might be better is only Redimthe byteTempbuffer if the intRead is less than 1024 (the redim is to prevent empty bytes from being added to the end of the array when there are less the 1024 bytes left to read from the networkstream) (basically is it more efficent to Redim every time or to go through and if statement and redim only if needed)

+2  A: 

This is definitely not the best way to do it : in each iteration of the loop, you're allocating a new buffer, bigger than the previous one... this could put a lot of pressure on the GC.

If you don't know the total length of the data, you could use a MemoryStream :

Private Function ReadFromBuffer(ByVal objReader As NetworkStream) As Byte()
    Dim intRead As Integer = 1024
    Dim byteTempbuffer(1023) As Byte
    Dim allBytes As New MemoryStream

    While intRead = 1024
        intRead = objReader.Read(byteTempbuffer, 0, 1024)
        allBytes.Write(byteTempbuffer, 0, intRead)
    End While

    Return allBytes.ToArray()
End Function
Thomas Levesque
Thank you I thought there was a better way :)
Jonathan