忧郁的小菜鸡 2020-09-01 09:28 采纳率: 0%
浏览 241
已结题

Java IO实现文件复制为什么transferFrom的实现方式速度会远快于MappedByteBuffer的实现方式?

文件大小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)

  • 写回答

4条回答 默认 最新

  • threenewbee 2020-09-01 09:55
    关注

    这个不好说,因为操作系统有文件缓存,磁盘也有缓存,就算调用同一个函数,也会出现第一次比第二次慢。
    你需要每次测试前都重新启动计算机

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!