1

Is there an actual performance difference when using write(byte[]) methods from FileOutputStream and BufferedOutputStream?

I tested both on HDD to write 500 MB file and the result was 13 and 12 seconds:

try(FileOutputStream out = new FileOutputStream(filePath1)) {
            out.write(readBytes);
}

and,

try(BufferedOutputStream out = new BufferedOutputStream( 
                           new FileOutputStream(filePath2))) {
            out.write(readBytes);
}

What am I missing about BufferedOutputStream efficiency?

user963241
  • 6,758
  • 19
  • 65
  • 93

1 Answers1

2

BufferedOutputStream is more efficient if you're writing data a little bit at a time: it batches the writes until it has "enough" data.

If you're writing it all at once, there's going to be no difference, because there's always enough data to fill the buffer; or you've reached the end of the data and need to close the stream.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • So, it will make a difference in only writing byte by byte i.e. write(int b)? – user963241 Jan 31 '17 at 14:44
  • Doesn't have to be one at a time; it's just if it's less than the buffer size (which is 8192 by default). – Andy Turner Jan 31 '17 at 14:45
  • As an addendum, if the array (fragment) to be written is as big or equal to the buffer size, the `BufferedOutputStream` will go out of the way and pass the array to the target stream directly. As a consequence, the worst case would be to repeatedly write chunks slightly smaller than the buffer size, which will not reduce the number of target write operations significantly, but add a copying overhead. In that case, the `BufferedOutputStream` *reduces* the performance. – Holger Feb 03 '17 at 17:10