How buffering in java.io package optimizes performance. I have read sources of main classes in the java.io package and I have noticed that I I wrap a stream into a buffered stream - then it the same work eventually happens, but somehow it is that it will increase performance. I understand buffered network will save some output traffic using caching, but how does file write benefit from caching. I assume the answer is somewhere out of Java - like in Jit compiler or underlying OS.
-
Perhaps [my answer to this question](https://stackoverflow.com/questions/33690884/why-does-the-buffered-writer-does-not-write-imediately-when-the-write-method-i/33691533#33691533) would help? Yes, you're doing the same "useful" work in the end, but the point is that you are reducing the amount of overhead (opening the file, seeking to the right place etc) by buffering it. – Andy Turner May 30 '17 at 08:22
-
@UPvoter no, it doesn't. Calling `write` in the buffered object [puts it into the buffer](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/BufferedWriter.java#143); and when the buffer is flushed, [the entire buffer is written to the underlying writer at once](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/BufferedWriter.java#128). – Andy Turner May 30 '17 at 08:35
-
will it not eventually call following. whitch is bute by byte... http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/OutputStream.java#OutputStream.write%28byte%5B%5D%29 – UPvoter May 30 '17 at 08:40
-
@UPvoter No it won't. It will call the underlying stream's `write(byte[])` or `write(byte[],int,int)` method. – user207421 May 30 '17 at 08:42
-
1Note that `FileOutputStream` overrides `write(byte[])` to call a native method. – Andy Turner May 30 '17 at 08:43
2 Answers
JNI calls and the syscalls underneath are not cheap. So if you read or write things a few bytes at a time this could become very expensive. Instead reading/writing to/from a buffer sized to a few kilobytes at a time and then just performing array-accesses (which often compile down to a single mov
instruction on x86) on the buffer can be much much cheaper.
But they are not universally faster, under some circumstances, when you want to transfer large chunks of data between direct bytebuffers, files or sockets the channel scatter/gather or transfer methods or memory-mapped files can be more performant since they avoid intermediate copying.

- 40,999
- 5
- 70
- 122
Mainly because it economizes vastly on system calls. Instead of calling the operating system once per byte, it calls it once per bufferload (8k bytes) or per flush()
.

- 305,947
- 44
- 307
- 483