I was wondering to myself whether or not writing a full message to a NetworkStream would be better than writing each section of a message in multiple Write calls. For example, would writing the message in full like such...
NetworkStream ns = tcpClient.GetStream();
byte[] message = Encoding.ASCII.GetBytes("This is a message.");
ns.Write(message, 0, message.Length);
... be a better idea than writing like this...
NetworkStream ns = tcpClient.GetStream();
byte[] message1 = Encoding.ASCII.GetBytes("This ");
byte[] message2 = Encoding.ASCII.GetBytes("is ");
byte[] message3 = Encoding.ASCII.GetBytes("a ");
byte[] message4 = Encoding.ASCII.GetBytes("message.");
ns.Write(message1, 0, message1.Length);
ns.Write(message2, 0, message2.Length);
ns.Write(message3, 0, message3.Length);
ns.Write(message4, 0, message4.Length);
Is there also much difference in program performance or networking performance for each method?
In terms of networking it will be the same. But on the client you don't need to have the entire message loaded in memory if you use the second approach. This could be useful when dealing with really big volumes of data. For example let's suppose that you want to send huge files. You could read those files in chunks so that you never need to load the entire file contents in memory and send it in chunks to the network. Only one chunk will ever be loaded at a time in-memory on the client.
But obviously if you already have the entire message in memory don't bother and write it in one shot to the network socket.