2

Which is preferable?

Assume this code before each:

byte[] data = Encoding.ASCII.GetBytes("Test Packet Message");
byte[] header = BitConverter.GetBytes(data.Length);

A:

clientStream.Write(header, 0, header.Length);
clientStream.Write(data, 0, data.Length);

B:

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);

A 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 A approach may be faster if sending a lot of data.

B 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 A as evidenced from this post.

What would be nice was if there was a way too accomplish A 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.

Community
  • 1
  • 1
John Smith
  • 8,567
  • 13
  • 51
  • 74
  • 3
    I think you are seriously over-thinking this, just write it to the stream. It's not clear to me why version 1 would result in two packets *on the wire* – BrokenGlass Sep 20 '11 at 21:13
  • 1
    Whether you or the TCP/IP driver concatenates the bytes doesn't matter much. Although the driver will probably do it is hair faster. This kind of micro-optimizations are a waste of your time. You need to start measuring instead of guessing. – Hans Passant Sep 20 '11 at 21:15
  • 1
    Hans Passant: Normally I would just do the first but [this post](http://stackoverflow.com/questions/6127419/faster-way-to-communicate-using-tcpclient/6137135#6137135) made me curious. – John Smith Sep 20 '11 at 21:20
  • @BrokenGlass: What do you think of [this post](http://stackoverflow.com/questions/6127419/faster-way-to-communicate-using-tcpclient/6137135#6137135)? It was largely the inspiration to this thread's creation.. – John Smith Sep 20 '11 at 22:04
  • @John: I admit defeat then - I didn't think this would matter at all - I'm still a doubter - but the details mentioned in that other post are beyond me. – BrokenGlass Sep 20 '11 at 22:17

1 Answers1

0

I would expect that the following method that accepts multiple buffers would achieve what you are looking for. However, I would want to test it to determine exactly what was being sent in terms of packets.

//Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Socket.Send Method (IList<ArraySegment<Byte>>, SocketFlags)

See the following post:

UDP - Can I send two datagram parts, and make the receiving end combine them into one?

Community
  • 1
  • 1
jzacharuk
  • 2,058
  • 1
  • 16
  • 22