Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it overkill to use BufferedWriter and BufferedOutputStream together?

I want to write to a socket. From reading about network IO, it seems to me that the optimal way to write to it is to do something like this:

OutputStream outs=null;
BufferedWriter out=null;
out =
  new BufferedWriter(
    new OutputStreamWriter(new BufferedOutputStream(outs),"UTF-8"));

The BufferedWriter would buffer the input to the OutputStreamWriter which is recommended, because it prevents the writer from starting up the encoder for each character.

The BufferedOutputStream would then buffer the bytes from the Writer to avoid putting one byte at a time potentially onto the network.

It looks a bit like overkill, but it all seems like it helps? Grateful for any help..

EDIT: From the javadoc on OutputStreamWriter:

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));
like image 691
Bruce Avatar asked Apr 03 '13 22:04

Bruce


1 Answers

The purpose of the Buffered* classes is to coalesce small write operations into a larger one, thereby reducing the number of system calls, and increasing throughput.

Since a BufferedWriter already collects writes in a buffer, then converts the characters in the buffer into another buffer, and writes that buffer to the underlying OutputStream in a single operation, the OutputStream is already invoked with large write operations. Therefore, a BufferedOutputStream finds nothing to combine, and is simply redundant.

As an aside, the same can apply to the BufferedWriter: buffering will only help if the writer is only passed few characters at a time. If you know the caller only writes huge strings, the BufferedWriter will find nothing to combine and is redundant, too.

like image 176
meriton Avatar answered Sep 23 '22 08:09

meriton