Send two packets (one with length and one with data) or send one concatenated packet?
<p>Which is preferable?</p>

<p>Assume this code before each:</p>

<pre><code>byte[] data = Encoding.ASCII.GetBytes("Test Packet Message");
byte[] header = BitConverter.GetBytes(data.Length);
</code></pre>

<p><strong>A:</strong></p>

<pre><code>clientStream.Write(header, 0, header.Length);
clientStream.Write(data, 0, data.Length);
</code></pre>

<p><strong>B:</strong></p>

<pre><code>byte[] bytes = new byte[header.Length + data.Length];

Buffer.BlockCopy(header, 0, bytes, 0, header.Length);
Buffer.BlockCopy(data, 0, bytes, header.Length, data.Length);

clientStream.Write(bytes, 0, bytes.Length);
</code></pre>

<p><strong>A</strong> has the benefit of not having to copy the bytes from one array to another so it is easier on the CPU (both clients and servers have to send and receive data so the <strong>A</strong> approach may be faster if sending a lot of data.</p>

<p><strong>B</strong> has the benefit of only sending one packet. People talk of the overhead of sending single small packets. Also, Nagle's algorithm may come in to play with <strong>A</strong> as evidenced from <a href="http://stackoverflow.com/questions/6127419/faster-way-to-communicate-using-tcpclient">this post</a>.</p>

<p>What would be nice was if there was a way too accomplish <strong>A</strong> without having to copy all the bytes from the header and data arrays to the bytes array but I'm not sure if that is possible.. Seems like there is a way to optimize it/make it more efficient but I'm not sure.</p>
