文件大小1.12G,我的代码如下:
@Test
public void test_4() throws Exception{
File file = new File("F:\\temporary\\readFile\\测试文件.rar");
File file2 = new File("F:\\temporary\\writeFile\\测试文件.rar");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
Long startTime = System.currentTimeMillis();
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = fis.getChannel();
outChannel = fos.getChannel();
outChannel.transferFrom(inChannel, 0, inChannel.size());
Long endTime = System.currentTimeMillis();
System.out.println("transferFrom 1G 文件耗时: "+(endTime - startTime));
}catch (Exception e) {
e.printStackTrace();
}finally {
inChannel.close();
outChannel.close();
}
}
@Test
public void test_5() throws Exception{
File file = new File("F:\\temporary\\readFile\\测试文件.rar");
File file2 = new File("F:\\temporary\\writeFile\\测试文件.rar");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
Long startTime = System.currentTimeMillis();
FileChannel inChannel = null;
FileChannel outChannel = null;
MappedByteBuffer mappedByteBuffer = null;
try {
inChannel = fis.getChannel();
outChannel = fos.getChannel();
mappedByteBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
outChannel.write(mappedByteBuffer);
Long endTime = System.currentTimeMillis();
System.out.println("MappedByteBuffer 1G 文件耗时: "+(endTime - startTime));
}catch (Exception e) {
e.printStackTrace();
}finally {
mappedByteBuffer.clear();
inChannel.close();
outChannel.close();
}
}
运行结果:
说明:我昨天使用 MappedByteBuffer 第一次运行时用了 17s 左右,第二次就降了很多,但也需要七八秒,这是由于操作系统虚拟内存可以自动缓存自动缓存内存页; 但如果第一次运行的是 transferFrom/transferTo ,运行时间是七八秒, 第二次运行就如上图,1 秒钟的时间都不到,我想不通这是为啥?为什么速度相差会如此之大,希望能有大佬替我解惑,万分感谢。
问题:希望能知道性能相差如此之大的原理? 再次感谢
问题已解决,原因是与映射区域大小有关,详情可以看我的博客(https://blog.csdn.net/weixin_41960204/article/details/108359390)