I created a file with 1,000,000 zeroes in it (980K) and measure how fast to copies it to another file (using buffered and non-buffered for both input and output) with default buffer size (8192 bytes). Surprisingly, buffering both input and output significantly improved performance. this is the result
While I understand that large file reads that exceeding the buffer size (8KB) might negate buffering benefits, I don't understand why the performance from using the buffer is still better than not using one (At least it takes less syscall). The only downside I see here seems to be unnecessary memory usage for the buffer itself.
Question is: 1.Except in memory-constrained environments where memory usage is a concern, why don't we always use buffer for both input and output?
- Why is it faster to copy a file when the output is buffered?
My code includes functions like t1(), t2(), t3(), and t4() which I will not share in full here since they are similar to the code provided:
static void t2() {
System.out.println("Copy file using BufferedInputStream (8192), with BufferOut");
long startTime = System.nanoTime();
try (BufferedInputStream br = new BufferedInputStream(new FileInputStream("text.txt"));
var bOut = new BufferedOutputStream(new FileOutputStream("text_3.txt"))) {
int i;
while ((i = br.read()) != -1) {
bOut.write(i);
}
} catch (IOException e) {
System.out.println(e);
}
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000000;
System.out.println("Duration: " + duration + " millisecond");
}
I've tried using in.transferTo with both buffered input&output and the result is even better (1 digit millisecond). I also plan to experiment with different buffer sizes. I read that the optimal size depends on the file system block size, which in my case is 4,096 bytes. Should I set the buffer size to 4,096, or is it the bigger the better?
i = br.read()). By using a buffer, you read more bytes at a time, and this is why the buffer is faster. Did I misunderstand what you are asking?read(), which reads a single byte at a time. That is slow for reasons already explained. The same is true forwrite(int). When you use the buffered input/output streams, it means there is abyte[]buffer being used behind the scenes. So, while from your own code it looks like you're still reading and writing a single byte at a time, you are actually reading and writing many more bytes at a time, reducing the number of system calls on both ends. IftransferTois truly faster, I would guess it's because the same buffer is being used for reading and writing.