In order to get the fastest transfer speeds over TCP in Java, which is better:
Option A:
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
Option B:
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
I've read that performance takes a hit when writing over 8 KiB to OutputStream, it was recommended that it'd be written to it in small chunks not pver 8 KiB at a time. 8 KiB is the default buffer size of a BufferedOutputStream.
However I've also read that when transfering data over the net it's good to flush out the bytes as quickly as possible. Meaning that using a buffer and writing in small chunks adds a unneeded overhead.
So, option A or option B? Which works best?
Right now I'm guessing option A gives highest transfer speeds while consuming a lot more CPU than option B. Option B might be better since it doesn't go that much slower but saves a lot of CPU.
--
Bonus question: Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB:
socket.setReceiveBufferSize(65536);
socket.setSendBufferSize(65536);
I tried setting it to 128 KiB on a test machine since I read that it could increase speeds but when the server got a couple of connections the CPU were at 100% instead of ~2% like when I left it alone. I guess 128 KiB is way too high unless you've got a good server that can handle that rush in traffic, but is it smart to set it to something like 32 KiB? I think the default was 8 KiB there for me.
("socket" is "java.net.Socket")
I don't know where you read all that nonsense but it is completely back to front. The more you write at a time to a TCP connection the better, and the more you read from it at a time ditto. I would always use a buffered stream, reader, or writer between the application and the socket streams. There are some cases like SSL where directly writing a byte at a time can cause a 40x data explosion.
Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB
You can't 'touch the TCP window size'. You can increase its maximum value via the APIs you mention, and that is indeed a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With