对于nio这个库可以直接操作内存的使用,可以做个对比,看哪种情况下适合使用。

import java.nio.ByteBuffer;

public class AccessDirectBuffer {
    //直接分配内存
    public static void directAccess() {
        long startTime = System.currentTimeMillis();
        ByteBuffer b = ByteBuffer.allocateDirect(500);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 99; j++)
                b.putInt(j);
            b.flip();
            for (int j = 0; j < 99; j++)
                b.getInt();
            b.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("directAccess:" + (endTime - startTime));
    }

    //分配堆内存
    public static void bufferAccess() {
        long startTime = System.currentTimeMillis();
        ByteBuffer b = ByteBuffer.allocate(500);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 99; j++)
                b.putInt(j);
            b.flip();
            for (int j = 0; j < 99; j++)
                b.getInt();
            b.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("bufferAccess" + (endTime - startTime));
    }

    public static void main(String args[]) {

        bufferAccess();
        directAccess();
        bufferAccess();
        directAccess();

    }
}


输出结果:

bufferAccess57
directAccess:28
bufferAccess55
directAccess:10


可以看到直接内存读写有较大优势,但是看看下面的情况:

import java.nio.ByteBuffer;

public class AllocDirectBuffer {
    public static void directAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {
            ByteBuffer.allocateDirect(1000);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("directAllocate:" + (endTime - startTime));
    }

    public static void bufferAllocate() {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {
            ByteBuffer.allocate(1000);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("bufferAllocate:" + (endTime - startTime));
    }

    public static void main(String[] args) {
        bufferAllocate();
        directAllocate();
        bufferAllocate();
        directAllocate();
    }
}

输出结果:

bufferAllocate:38
directAllocate:282
bufferAllocate:71
directAllocate:403


可以看到在内存空间申请上,直接内存毫无优势。


如果内存空间本身需要频繁申请,则不适合使用直接内存。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐