title: Sockets: BufferedOutputStream or just OutputStream?
body: <p>In order to get the fastest transfer speeds over TCP in Java, which is better:</p>
  
  <p>Option A:</p>
  
  <pre><code>InputStream in = socket.getInputStream();
  OutputStream out = socket.getOutputStream();
  </code></pre>
  
  <p>Option B:</p>
  
  <pre><code>BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
  BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>So, option A or option B? Which works best?</p>
  
  <p>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.</p>
  
  <p>--</p>
  
  <p>Bonus question: Is it a good idea to touch the TCP window size? For example by setting it to 64 KiB:</p>
  
  <pre><code>socket.setReceiveBufferSize(65536);
  socket.setSendBufferSize(65536);
  </code></pre>
  
  <p>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.</p>
  
  <p>("socket" is "java.net.Socket")</p>