Is buffered output stream more efficient than input stream in Java?

Bored earlier today, I began to think about the relative performance of buffered and unbuffered byte streams in Java As a simple test, I downloaded a reasonably large text file and wrote a short program to determine the effect of buffer stream when copying files Four tests were conducted:

>Copy files using unbuffered input and output byte streams. > Copy files using buffered input streams and unbuffered output streams. > Copy files using unbuffered input streams and buffered output streams. > Use buffered input and output streams to copy files

Not surprisingly, buffered input and output streams are several orders of magnitude faster than unbuffered streams However, the really interesting thing (for me at least) is the speed difference between 2 and 3 Some sampling results are as follows:

Unbuffered input,unbuffered output
Time: 36.602513585

Buffered input,unbuffered output
Time: 26.449306847

Unbuffered input,buffered output
Time: 6.673194184

Buffered input,buffered output
Time: 0.069888689

For those interested, the code can be used here at GitHub Anyone can understand why the time of cases 2 and 3 is so asymmetric?

Solution

When you read a file, the file system and device under it will be cached at various levels They almost never read a byte; They read for a block When the next byte is subsequently read, the block will be in cache, so it will be faster

Therefore, if your buffer size is the same as the block size, buffering the input stream won't actually get all the benefits (it saves some system calls, but it won't save you too much in terms of actual physical I / O)

When you write a file, the file system can't cache it for you because you don't write to its backlog It may buffer your output, but it must have an experienced guess about the frequency of flushing the buffer By buffering the output yourself, you can let the device do more work immediately because you build the backlog manually

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>