Question

I'm trying to figure out what size I should be setting my byteSize to when reading from a NetworkStream. Whats the pros and con of using a smaller or large number?

A lot of examples I have seen use 256. Why?

int byteSize = 256;

TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
Byte[] bytes = new Byte[byteSize];

TcpClient client = server.AcceptTcpClient();

NetworkStream stream = client.GetStream();
int i = 0;

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    // Do stuff with the stream
}
Was it helpful?

Solution

Make it too small and you'll lose some efficiency from .NET having to make an operating system call more frequently to refill the buffer. Make it too big and you waste some memory.

It is not that critical but 256 is on the low end. A very common I/O buffer size is 4096 bytes. It is a magic number in Windows, the size of a memory page. Albeit that the buffer will exactly straddle one page only by accident.

OTHER TIPS

Whatever you set it according to your code i is the actual bytes read from socket, so a byteSize doesn't help you if i is pretty much smaller than byteSize.

Inside your while you should check if i is smaller that byteSize and if so, copy the first i bytes of your byte (byte array) to a safe place i.e a memory stream or a file stream and continue to read socket to get to the end of network stream (where i = 0). 1024, 2048 and 4096 seems good depending on your network speed, available memory and threads which are using such a buffer. For example using 100 threads with 1024 buffer size cost you 100 KB of RAM which is nothing at today's hardware scale.

Personally most of the times use a smart buffer, I mean at run time I check read amount against buffer size and correct it to get a better result (albeit if it worth according to the project).

I just stumble across this now, in case anyone else may do the same this is how I will go about setting the Byte size https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.getstream?view=netframework-4.7.2

int byteSize = new byte[tcpClient.ReceiveBufferSize];

Byte[] bytes = new Byte[byteSize];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top