Skip to main content

socket.getInputStream() more performant than BufferedInputStream?

2 replies [Last post]
Joined: 2006-01-26


I want to get your opinion:

which of the two implementations is more performant?

1. InputStream is = socket.getInputStream();
2. InputStream is = new BufferedInputStream(socket.getInputStream);

I think the first one is better because it reads directly and native from the socket whereas the second one first copies the data from the socket to an internal byte array. So if using[]) the first method should be better?! Am I right?!??


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-07-11

I think it also depends on what your application is capable of handling. I.e.
can you afford to buffer the read/write operations from a latency perspective.

Regardless, the buffered approach should result in fewer calls to read(), with
a larger amount of data per call, but you'll end up postponing the I/O operation
until the buffer is filled or until you explicitly flush it.

One thing to watch out for, though, is that larger i/o buffers in socket read/write
operations will force the native read and write methods down a path that results
in calls to malloc(), and some default malloc() implementations don't necessarily
scale very well. This path is triggered when the buffer size is >= 8k. When the
buffer size is >=64k and you are doing a write, the native code will go into a
loop that writes 64k at a time, thus 'chunking' the output. See

If you are writing new code, I would suggest that you look at the SocketChannel
class and consider using direct ByteBuffers. This generally results in more efficient
I/O by reducing copying of data from byte[] to/from ByteBuffers and avoiding the
chunking code when writing to the sockets. This assumes, though, that you can
make use of the ByteBuffer directly, and not have to copy the data to a byte[] or
char[] or something to make use of the data.

Note that ByteBuffer.allocateDirect() also results in a call to malloc() and can
become a bottleneck. This is one of the rare cases where pooling is likely a win;
allocate your direct ByteBuffer once and carve out view buffers and use the
view buffers for the individual I/O operations - don't allocate a new direct
ByteBuffer for each I/O operation.


Joined: 2004-01-07

It really depends ... if you read many small chunks (e.g. 100's of bytes) the buffered stream is way faster because its quite importat for the jvm to go out to native code (call into the OS) and for just a few bytes.

The BufferedInputStream on the other side reads large chunks of data, and if you read small chunks they come directly from the byte[] without any native code.
Performance-difference can be sometimes really large, I suggest you test over a socket by sending single bytes.

lg Clemens