PrintStream被缓冲,通过在每个print()之后添加刷新操作,速度性能应该会显着降低,但完全没有降低,如下面的代码片段所示。
// PrintStream is buffered but takes 4228ms to complete long start = System.currentTimeMillis(); try (PrintStream ps = new PrintStream(new FileOutputStream("1.txt") )) { for (int i = 0; i < 1_000_000; i++) { ps.print(i + " "); } } long stop = System.currentTimeMillis(); System.out.println(stop - start); // PrintStream is buffered, but with auto-flush takes 4140ms to complete, no degraded speed implying flush did nothing start = System.currentTimeMillis(); try (PrintStream os = new PrintStream(new FileOutputStream("1.txt") )) { for (int i = 0; i < 1_000_000; i++) { os.print(i + " "); os.flush(); } } stop = System.currentTimeMillis(); System.out.println(stop - start);
在https://stackoverflow.com/a/42682673/10082400处的回复写道:
虽然
PrintStream
的内部是“缓冲的”,但是write方法会将内部缓冲区刷新到每个write()
上的基础流。内部“缓冲区”实际上只是在处理字符到字节的转换
在PrintStream
(尤其是write()
,print()
和println()
的实现中,
我看到所有写方法仅在flush()
为真且其表示的条件为真时才调用autoFlush
。与答案中的“ write方法将内部缓冲区刷新到每个write()
上的基础流”相反吗?
我还看到PrintStream
间接使用the buffer in its BufferedWriter
field textOut
。 PrintStream
的内部缓冲区在哪里?