gpt4 book ai didi

java - 就性能而言,在什么时候用 BufferedOutputStream 包装 FileOutputStream 才有意义?

转载 作者:IT老高 更新时间:2023-10-28 20:40:25 24 4
gpt4 key购买 nike

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

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

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

最佳答案

当写入小于缓冲区大小时,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 - 就性能而言,在什么时候用 BufferedOutputStream 包装 FileOutputStream 才有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com