开发者

Java I/O classes and performance

Reading Thinking in Java 4th ed. I've got some doubts开发者_开发百科 about I/O operations performance: I've read that it's better to "wrap" InputStream objects in BufferedInputStream, but in my mind I can't see any difference. Isn't i.e. file operations already buffered? What's the advantages of file buffered write?


The system's IO buffering is on a different level than the Buffered*putStream.

Each call on FileOutputStream.write(...) induces a native method call (which is typically more costly than a java-internal call), and then a context switch to the OS' kernel to do the actual writing. Even if the kernel (or the file system driver or the harddisk controller or the harddisk itself) is doing more buffering, these costs will occur.

By wrapping a BufferedOutputStream around this, we will call the native write method only much less often, thus allowing much higher throughput.

(The same is valid for other types of IO, of course, I just used FileOutputStream as an example.)


Isn't i.e. file operations already buffered?

Maybe, maybe not - depending on the OS, the HD used, the way of access (e.g. reading big consecutive blocks vs randomly accessing small blocks all over the place), etc. In the worst case, adding a BufferedInputStream probably won't harm performance noticeably. In the best case, it can improve it by magnitudes (replacing many little file accesses by one big read/write).


An InputStream will only request as much data as you request, so if you request 1000 characters one character at a time, that will turn out to be 1000 seperate disk accesses, which will become pretty slow.

A BufferedInputStream however will request data from the InputStream in larger chunks, thus reducing the need for seperate disk accesses.

The same goes for output, instead of writing every character seperately, there are fewer physical disk writes with a BufferedOutputStream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜