我有一个模块,负责读取,处理和将字节写入磁盘。字节通过UDP传入,并且在组装完各个数据报之后,要处理并写入磁盘的最终字节数组通常在200字节至500,000字节之间。有时,在组装后,会有字节数组超过500,000个字节,但是这些相对很少见。
我目前正在使用 FileOutputStream
的 write(byte\[\])
method。我还尝试将FileOutputStream
包装在 BufferedOutputStream
中,包括使用the constructor that accepts a buffer size as a parameter。
看来使用BufferedOutputStream
趋于稍微提高性能,但是我才刚刚开始尝试使用不同的缓冲区大小。我只有一组有限的示例数据可以使用(示例运行中的两个数据集,可以通过我的应用程序进行传递)。给定我知道的数据信息,我是否可以运用一般的经验法则来尝试计算最佳缓冲区大小,以减少磁盘写操作并最大程度地提高磁盘写性能?
最佳答案
当写入小于缓冲区大小时,例如BufferedOutputStream会有所帮助。 8 KB。对于较大的写入,它无济于事,也不会使其变得更糟。如果您的所有写操作都大于缓冲区大小,或者每次写操作后始终都使用flush(),则我不会使用缓冲区。但是,如果您的写入中有很大一部分小于缓冲区大小,并且您并非每次都使用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;
}
关于java - 在性能上,在什么时候用BufferedOutputStream包裹FileOutputStream才有意义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8712957/