java - 使用 ByteBuffer 在 channel 上进行 I/O 操作 - 性能比较

标签 java performance bytebuffer channels

我想使用 ByteBuffer 对 channel 执行 I/O 操作。最后我想出了三个解决方案:

FileChannel inChannel = new FileInputStream("input.txt").getChannel();
FileChannel outChannel = new FileOutputStream("output.txt").getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);

方法一:使用hasRemaining()

while (inChannel.read(buf) != -1) {
    buf.flip();    
    while (buf.hasRemaining()) {
        outChannel.write(buf);
    }    
    buf.clear();
}

方法二:使用compact()

while (inChannel.read(buf) != -1 || buf.position() > 0) {
    buf.flip();
    outChannel.write(buf);
    buf.compact();
}

方法三:混合模型

while (inChannel.read(buf) != -1) {
    buf.flip();
    outChannel.write(buf);
    buf.compact();
}
// final flush of pending output
while (buf.hasRemaining())
    outChannel.write(buf);

问题是:哪种方法的性能和吞吐量最高?

最佳答案

您为什么要使用 compact()? - 它可能涉及重复复制大量数据。

如果您没有充分的理由在写入所有先前读取的数据之前执行另一次读取,那么您可以采用第一种方法。

哦,顺便说一下:如果您只是想将数据从一个文件复制到另一个文件,请查看 transferTo() , 或 transferFrom() .这是文件复制的最高性能方式,因为这可能使用底层操作系统的非常高效的操作,例如 DMA。

(编辑:transferTo() 等。当然不需要需要任何 ByteBuffer,混合两种想法:))

关于java - 使用 ByteBuffer 在 channel 上进行 I/O 操作 - 性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7944438/

相关文章:

java - 不确定 addRating 和 getAverage 方法是否正确

java - 编译 Java 应用程序以利用 Kafka

performance - 在 Matlab 循环中使用变量做某事比什么都不做更快

java - 从 ByteBuffer 中移除前 n 个字节

java.nio.ByteBuffer.slice() 线程行为?

java - 通过ByteBuffer传输字符串

java - "Iterable<Element> cannot be cast to List<Element>"- 't ` 列表 ` a type of ` 是可迭代的吗?

java - 了解 JPA 延迟加载

javascript - 如何使移动设备中的 jquery setinterval 移动更顺畅?

wpf - WPF是否可以在没有DirectX的情况下运行?