What is the fastest way of sending array of 1000 bytes down the TCP Socket using Java? And how to measure it?
If my code that sends 1000 bytes arrya 25_000 times to "localhost" of the same machine would the measurement be fair?
How to achieve the fastest transfer rate?
ByteBuffer buffer = ByteBuffer.allocateDirect( 1000 );
SocketChannel clientSocketChannel = SocketChannel.open( new InetSocketAddress( "localhost", 8888 ) );
clientSocketChannel.socket().setTcpNoDelay( true );
// empty array of bytes
byte[] array = new byte[BUFFER_SIZE];
for ( int i = 0; i < 25_000; i++ ) {
buffer.put( array );
buffer.flip();
long start = System.nanoTime();
// ==========================================
do {
int len = clientSocketChannel.write( buffer );
if (len < 0)
throw new EOFException();
} while (buffer.hasRemaining());
// ==========================================
long elapsed = System.nanoTime() - start;
System.out.println( i + ":\t" + elapsed );
buffer.flip();
}
System.out.println( "Client: finished" );
I get these numbers during execution:
14669: 14543
14670: 62877
14671: 14971
14672: 13687
14673: 70576
14674: 20104
14675: 16254
14676: 60311
14677: 15826
14678: 15826
14679: 18820
14680: 13688
14681: 12832
14682: 12832
14683: 14115
14684: 12831
14685: 12832
14686: 14971
14687: 4705
14688: 4277
14689: 4278
14690: 4277
14691: 3849
14692: 4705
14693: 4706
14694: 4278
14695: 4705
14696: 4277
14697: 4277
14698: 4705
14699: 3849
14700: 4277
14701: 4277
so for 100 iterations it goes faster - then goes back to
15067: 14115
15068: 16254
15069: 19248
15070: 13687
15071: 13259
15072: 14115
15073: 14970
15074: 15827
15075: 14543
15076: 16682
15077: 14116
15078: 16254
15079: 14543
15080: 16253
iperf utility shows me that loppback can transfer 200 MBytes per second. That is approx 4 microseconds per 1000 bytes. So durign execution of my program transfer rate indeed approcahes this rate - but drops from time to time to 14-15 microseconds per 1000 bytes message. There is no JIT involved here as JIT is happening duirng first 10.000 iterations. No class loading, no garbage collection