在PrintStream中如何使用缓冲区和刷新功能?

时间:2019-05-26 23:27:46

标签: java io

PrintStream is buffered, but flush does not degrade performance and BufferedOutputStream speeds up performance处的问题是

  

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 textOutPrintStream的内部缓冲区在哪里?

0 个答案:

没有答案