A DataInputStream is not buffered, so each read operation on a DataInputStream
object is going to result in one or more reads on the underlying socket stream, and that could result in multiple system calls (or the equivalent).
A system call is typically 2 to 3 orders of magnitude more expensive than a regular method call. Buffered streams work by reducing the number of system calls (ideally to 1), at the cost of adding an extra layer of regular method calls. Typically using a buffered stream replaces N
syscalls with 1
syscall and N
extra method calls. If N
(i.e. the ratio of stream method calls to syscalls) is greater than 1
, you win.
It follows that the only cases where putting a BufferedInputStream
between the socket stream and the DataInputStream
is not a "win" are:
- when the application only makes one
read...()
call and that can be satisfied by a single syscall,
- when the application only does large
read(byte[] ...)
calls, or
- when the application doesn't read anything.
It sounds like these don't apply in your case.
Besides, even if they do apply, the overhead of using a BufferedInputStream
*when you don't need to is relatively small. By contrast, the overhead of not using a BufferedInputStream
when you do need to can be huge.
One final point, the actual amount of data read (i.e. the size of the messages) is pretty much irrelevant to the buffered versus unbuffered conundrum. What really matters is the way that data is read; i.e. the sequence of read...()
calls that your application will make.