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)

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

transferFrom属于零拷贝技术,零拷贝中有个写时复制技术,其指的是当多个进程共享同一块数据时,如果其中一个进程需要对这份数据进行修改,那么将其拷贝到自己的进程地址空间中,如果只是数据读取操作则不需要进行拷贝操作。也就是说你第二次执行的时候,不需要在进行拷贝操作了,所以节省了大量时间

transferFrom属于零拷贝技术,是电脑操作系统自带的方式; 减少了往用户态copy的一次过程;类似我楼上说的,如果不需要操作数据,只是copy,则直接从Acopy到B , 不需要经过A->用户态->B

这个属于java的nio问题,而java的nio也不是java问题是属于操作系统层面,操作系统提供了sendfile,mmap,splice,direct io等系统调用,这个概念挺大的,一次io过程中会涉及到硬件内存,内核,java的堆内存这三方的内存拷贝和4次内核态和用户态转换,sendfile利用dma技术将4次cpu拷贝变成2次dma拷贝,read和write两次系统调用变成sendfile一次系统调用