性能:Java中的BufferedOutputStream与FileOutputStream

性能:Java中的BufferedOutputStream与FileOutputStream,java,Java,我已经读到BufferedOutputStream类提高了效率,必须以这种方式与FileOutputStream一起使用- BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("myfile.txt")); 对于写入同一个文件,下面的语句也是有效的- FileOutputStream fout = new FileOutputStream("myfile.txt"); 但推荐的方法是使用缓冲区进行

我已经读到BufferedOutputStream类提高了效率,必须以这种方式与FileOutputStream一起使用-

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("myfile.txt"));
对于写入同一个文件,下面的语句也是有效的-

FileOutputStream fout = new FileOutputStream("myfile.txt");
但推荐的方法是使用缓冲区进行读/写操作,这就是为什么只有我自己也喜欢使用缓冲区进行读/写操作的原因

但我的问题是如何衡量上述两种说法的表现。他们有没有什么工具或者什么的,不知道到底是什么?但这将有助于分析它的性能


作为JAVA语言的新手,我很想了解它。

缓冲只有在读写效率低下的情况下才有用。对于读取,它有助于让您逐行读取,即使您可以使用read(byte[])或read(char[])更快地读取字节/字符。对于写入,它允许您使用缓冲区缓冲要通过I/O发送的内容,并仅在刷新时发送(请参阅PrintWriter(PrintOutputStream(?).setAutoFlush())

但是,如果您只是试图以尽可能快的速度读写,缓冲并不能提高性能

有关高效读取文件的示例:

File f = ...;
FileInputStream in = new FileInputStream(f);
byte[] bytes = new byte[(int) f.length()]; // file.length needs to be less than 4 gigs :)
in.read(bytes); // this isn't guaranteed by the API but I've found it works in every situation I've tried
与低效阅读相比:

File f = ...;
BufferedReader in = new BufferedReader(f);
String line = null;
while ((line = in.readLine()) != null) {
  // If every readline call was reading directly from the FS / Hard drive,
  // it would slow things down tremendously. That's why having a buffer 
  //capture the file contents and effectively reading from the buffer is
  //more efficient
}

这些数字来自使用SSD的MacBookPro笔记本电脑

  • BufferedFileStreamarayBatchRead(809716.60-911577.03字节/毫秒)
  • 缓冲文件流字节(136072.94字节/毫秒)
  • FileInputStreamArrayBatchRead(121817.52-1022494.89字节/毫秒)
  • FileInputStreamByteBufferRead(118287.20-1094091.90字节/毫秒)
  • FileInputStreamDirectByteBufferRead(130701.87-956937.80字节/毫秒)
  • FileInputStreamReadPerByte(1155.47字节/毫秒)
  • RandomAccessFileArrayBatchRead(120670.93-786782.06字节/毫秒)
  • RandomAccessFileReadPerByte(1171.73字节/毫秒)
当数字存在一定范围时,它会根据所用缓冲区的大小而变化。缓冲区越大,达到某一点的速度就越快,通常在硬件和操作系统中的缓存大小附近

如您所见,单独读取字节总是很慢。将读取分为块是一种很容易的方法。这可能是1k/ms和136k/ms(或更多)之间的差异

这些数字有点旧,它们会随着设置的不同而变化很大,但它们会给你一个想法。可以找到生成数字的代码,编辑Main.java以选择要运行的测试


一个优秀的(和更严格的)编写基准测试的框架是。可以找到学习如何使用JMH的教程。

低效的阅读或写作是什么意思@ControlAltDel@user7876966我更新了我的答案,列举了高效和低效读取的例子。这意味着从FS/HDD中已经可用的文件中读取是低效的,而从c中读取是低效的md即用户输入数据是有效的。这取决于这种读/写类型,我们应该在BufferedReader/BufferedWriter和FileInputStream/FileOutputStream之间切换吗@ControlAltDel@user7876966不,您不明白我写的内容表明使用缓冲流可以减少系统调用,所以理论上应该是这样的总是更好地使用它们。