【问题标题】:At what point does wrapping a FileOutputStream with a BufferedOutputStream make sense, in terms of performance?就性能而言,在什么时候用 BufferedOutputStream 包装 FileOutputStream 才有意义?
【发布时间】:2012-02-01 12:48:09
【问题描述】:

我有一个模块负责读取、处理和写入字节到磁盘。字节通过 UDP 传入,并且在组装各个数据报之后,被处理并写入磁盘的最终字节数组通常在 200 字节到 500,000 字节之间。偶尔会有字节数组,组装后超过50万字节,但这种情况比较少见。

我目前正在使用FileOutputStreamwrite(byte\[\]) method。我还在尝试将FileOutputStream 包装在BufferedOutputStream 中,包括使用the constructor that accepts a buffer size as a parameter

似乎使用BufferedOutputStream 的性能会稍好一些,但我才刚刚开始尝试不同的缓冲区大小。我只有一组有限的示例数据可供使用(来自示例运行的两个数据集,我可以通过我的应用程序进行管道传输)。考虑到我所知道的关于我正在写入的数据的信息,是否有一个通用的经验法则可以用来尝试计算最佳缓冲区大小以减少磁盘写入并最大限度地提高磁盘写入的性能?

【问题讨论】:

    标签: java file-io io fileoutputstream bufferedoutputstream


    【解决方案1】:

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

    您可能会发现将缓冲区大小增加到 32 KB 或更大会带来边际改进,或者会使情况变得更糟。 YMMV


    您可能会发现 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;
    }
    

    【讨论】:

    • 我还没有找到的东西 - Java 6 中 BufferedOutputStream 的默认缓冲区大小是多少?您提到 8KB - 这是 Java 中的默认值吗? 1.4.2 的 Javadocs 说缓冲区是 512 字节,这意味着我写的大部分内容往往落在每个数组 200 到 400 字节之间。但是,此信息已从 Java 6 文档中删除。
    • @Thomas - looking at the source code,默认大小为 8192。我假设他们删除了默认大小规范,以便在出现新的“最明智的默认值”时能够更改它。如果有一个特定的缓冲区大小很重要,您可能需要明确指定它。
    • @gustafc 谢谢。我总是忘记我可以看Java源代码。
    • 我的另一个问题是,大于缓冲区大小的写入是否比非缓冲写入的性能更差。我想不出它会变得更糟的原因,尽管缓冲区大小越大,缓冲区被填满、写入和再次填满的次数就越多。所以我可能也需要尝试一下。
    【解决方案2】:

    我最近一直在尝试探索 IO 性能。据我观察,直接写信给FileOutputStream 会带来更好的结果;我将其归因于FileOutputStreamwrite(byte[], int, int) 的原生调用。此外,我还观察到,当BufferedOutputStream 的延迟开始向直接FileOutputStream 收敛时,它的波动更大,甚至可以突然翻倍(我还没有找到原因)。

    附:我正在使用 Java 8,现在无法评论我的观察是否适用于以前的 Java 版本。

    这是我测试的代码,我的输入是一个大约 10KB 的文件

    public class WriteCombinationsOutputStreamComparison {
        private static final Logger LOG = LogManager.getLogger(WriteCombinationsOutputStreamComparison.class);
    
    public static void main(String[] args) throws IOException {
    
        final BufferedInputStream input = new BufferedInputStream(new FileInputStream("src/main/resources/inputStream1.txt"), 4*1024);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int data = input.read();
        while (data != -1) {
            byteArrayOutputStream.write(data); // everything comes in memory
            data = input.read();
        }
        final byte[] bytesRead = byteArrayOutputStream.toByteArray();
        input.close();
    
        /*
         * 1. WRITE USING A STREAM DIRECTLY with entire byte array --> FileOutputStream directly uses a native call and writes
         */
        try (OutputStream outputStream = new FileOutputStream("src/main/resources/outputStream1.txt")) {
            final long begin = System.nanoTime();
            outputStream.write(bytesRead);
            outputStream.flush();
            final long end = System.nanoTime();
            LOG.info("Total time taken for file write, writing entire array [nanos=" + (end - begin) + "], [bytesWritten=" + bytesRead.length + "]");
            if (LOG.isDebugEnabled()) {
                LOG.debug("File reading result was: \n" + new String(bytesRead, Charset.forName("UTF-8")));
            }
        }
    
        /*
         * 2. WRITE USING A BUFFERED STREAM, write entire array
         */
    
        // changed the buffer size to different combinations --> write latency fluctuates a lot for same buffer size over multiple runs
        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("src/main/resources/outputStream1.txt"), 16*1024)) {
            final long begin = System.nanoTime();
            outputStream.write(bytesRead);
            outputStream.flush();
            final long end = System.nanoTime();
            LOG.info("Total time taken for buffered file write, writing entire array [nanos=" + (end - begin) + "], [bytesWritten=" + bytesRead.length + "]");
            if (LOG.isDebugEnabled()) {
                LOG.debug("File reading result was: \n" + new String(bytesRead, Charset.forName("UTF-8")));
            }
        }
    }
    }
    

    输出:

    2017-01-30 23:38:59.064 [INFO] [main] [WriteCombinationsOutputStream] - Total time taken for file write, writing entire array [nanos=100990], [bytesWritten=11059]
    
    2017-01-30 23:38:59.086 [INFO] [main] [WriteCombinationsOutputStream] - Total time taken for buffered file write, writing entire array [nanos=142454], [bytesWritten=11059]
    

    【讨论】:

    • 我运行了类似的测试,我可以确认使用BufferedOutputStream 使得写入文件的速度不是更快而是更慢,很可能是因为正在写入的数据在从 JVM 到操作系统到物理介质。
    • @GOTO 感谢您的确认。是否有任何您可能知道的资源可以帮助我更深入地了解 IO 和内部缓存的工作原理?
    • 并非如此。如果它有助于谷歌搜索,文件缓存组件在 Windows 中称为缓存管理器,在 Linux 中称为页面缓存。硬盘和其他存储设备也带有不同类型的 I/O 缓存(尽管基本内容可能相同)。
    猜你喜欢
    • 2013-10-07
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2011-10-22
    • 2014-07-21
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多