UPvoter
UPvoter

Reputation: 45

How buffering in java.io package optimizes performance

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.

Upvotes: 2

Views: 450

Answers (2)

the8472
the8472

Reputation: 43042

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.

Upvotes: 3

user207421
user207421

Reputation: 310885

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().

Upvotes: 1

Related Questions