繁体   English   中英

性能:Java中的BufferedOutputStream与FileOutputStream

[英]Performance : BufferedOutputStream vs FileOutputStream in Java

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

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("myfile.txt"));

对于下面的语句写入同一文件也是有效的-

FileOutputStream fout = new FileOutputStream("myfile.txt");

但是推荐的方法是使用Buffer进行读/写操作,这就是为什么我只更喜欢使用Buffer的原因。

但是我的问题是如何衡量上述2条语句的性能。 他们是任何工具还是某种东西,不知道到底是什么? 但这对于分析其性能很有用。

作为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的MacBook Pro笔记本电脑。

  • BufferedFileStreamArrayBatchRead(809716.60-911577.03字节/毫秒)
  • BufferedFileStreamPerByte(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是一个出色的(更严格)基准测试框架。 这里可以找到学习如何使用JMH的教程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM