TcpClient performance - sending 4 scalar values ​​is much slower than sending 1 byte array containing all values

I am writing an application in which two applications (for example, a server and a client) exchange data through a TCP connection on a local hosting.

The code is pretty performance critical, so I try to optimize as best as possible.

Below is the code from the server application. To send messages, my naive approach was to create a BinaryWriter from the TcpClient stream and write each message value through a BinaryWriter. So let the message consist of 4 values; long followed by a Bolean meaning, and then two more long; naive approach:

TcpClient client = ...;
var writer = new BinaryWriter(client.GetStream());

// The following takes ca. 0.55ms:

writer.Write((long)123);
writer.Write(true);
writer.Write((long)456);
writer.Write((long)2);

With a runtime of 0.55 ms, it looks pretty slow. Then I tried the following:

TcpClient client = ...;

 // The following takes ca. 0.15ms:

var b1 = BitConverter.GetBytes((long)123);
var b2 = BitConverter.GetBytes(true);
var b3 = BitConverter.GetBytes((long)456);
var b4 = BitConverter.GetBytes((long)2);

var result = new byte[b1.Length + b2.Length + b3.Length + b4.Length];
Array.Copy(b1, 0, result, 0, b1.Length);
Array.Copy(b2, 0, result, b1.Length, b2.Length);
Array.Copy(b3, 0, result, b1.Length + b2.Length, b3.Length);
Array.Copy(b4, 0, result, b1.Length + b2.Length + b3.Length, b4.Length);

client.GetStream().Write(result, 0, result.Length);

0,15 , 0,55 , 3-4 .

... ? , ( )?

, , - , BinaryWriter; , , (, 10 000 ) , , .Flush() (, ).

, , ? - , ? Winsock (, , , )?

!

+4
2

-, - . - , , , / .

, , . , -.

0

, Interprocess Communication (IPC), TCP. IPC (. Interprocess Communications Microsoft Dev Center). ( /), , .

:

. . .

, ?

:

  • . , .
  • . , , "" .

, , , , , TLB / . , -, ( ) , / . , . .

TCP, , . BufferedStream, TCP BinaryWriter. , , BufferedStream , NetworkStream. . TCP? BufferedStream.Write throw " " ? StackOverflow.

, # Sockets vs Pipes, IPC # - , .NET BufferedStream? ? StackOverflow.

0

Source: https://habr.com/ru/post/1695413/


All Articles