在性能方面,在什么时候用BufferedOutputStream包装FileOutputStream是有意义的?

Tho*_*ens 44 java io file-io fileoutputstream bufferedoutputstream

我有一个模块负责读取,处理和写入磁盘的字节.字节通过UDP传入,在汇编各个数据报之后,处理并写入磁盘的最终字节数组通常在200字节到500,000字节之间.偶尔会有一些字节数组,在汇编后,超过500,000字节,但这些数组相对较少.

我现在正在使用FileOutputStreamwrite(byte\[\])方法.我也在尝试包装FileOutputStreamin BufferedOutputStream,包括使用接受缓冲区大小作为参数的构造函数.

似乎使用的BufferedOutputStream是趋向于略微更好的性能,但我只是开始尝试不同的缓冲区大小.我只有一组有限的样本数据可供使用(来自样本运行的两个数据集,我可以通过我的应用程序管道).是否有一般的经验法则我可以应用于尝试计算最佳缓冲区大小以减少磁盘写入并最大化磁盘写入的性能,因为我知道有关我正在编写的数据的信息?

Pet*_*rey 32

当写入小于缓冲区大小(例如8 KB)时,BufferedOutputStream会有所帮助.对于较大的写入,它没有帮助,也没有使它变得更糟.如果所有写入都大于缓冲区大小,或者每次写入后总是刷新(),我就不会使用缓冲区.但是,如果您的写入的大部分比缓冲区大小少,并且每次都不使用flush(),那么它的价值就是.

您可能会发现将缓冲区大小增加到32 KB或更大会使您获得边际改进,或者使其变得更糟.因人而异


您可能会发现BufferedOutputStream.write的代码很有用

/**
 * Writes <code>len</code> bytes from the specified byte array
 * starting at offset <code>off</code> to this buffered output stream.
 *
 * <p> Ordinarily this method stores bytes from the given array into this
 * stream's buffer, flushing the buffer to the underlying output stream as
 * needed.  If the requested length is at least as large as this stream's
 * buffer, however, then this method will flush the buffer and write the
 * bytes directly to the underlying output stream.  Thus redundant
 * <code>BufferedOutputStream</code>s will not copy data unnecessarily.
 *
 * @param      b     the data.
 * @param      off   the start offset in the data.
 * @param      len   the number of bytes to write.
 * @exception  IOException  if an I/O error occurs.
 */
public synchronized void write(byte b[], int off, int len) throws IOException {
    if (len >= buf.length) {
        /* If the request length exceeds the size of the output buffer,
           flush the output buffer and then write the data directly.
           In this way buffered streams will cascade harmlessly. */
        flushBuffer();
        out.write(b, off, len);
        return;
    }
    if (len > buf.length - count) {
        flushBuffer();
    }
    System.arraycopy(b, off, buf, count, len);
    count += len;
}
Run Code Online (Sandbox Code Playgroud)

  • @Thomas - [查看源代码](http://www.docjar.com/html/api/java/io/BufferedOutputStream.java.html#51),默认大小为8192.我假设他们删除了默认大小规格,以便在出现新的"最合理的默认值"时能够更改它.如果具有特定的缓冲区大小很重要,您可能希望明确指定它. (3认同)