java堆和直接内存的区别

NIO的Buffer提供了一个可以不经过JVM内存直接访问系统物理内存的类——DirectBuffer。 DirectBuffer类继承自ByteBuffer,但和普通的ByteBuffer不同,普通的ByteBuffer仍在JVM堆上分配内存,其最大内存受到最大堆内存的限制;而DirectBuffer直接分配在物理内存中,并不占用堆空间,其可申请的最大内存受操作系统限制。

直接内存的读写操作比普通Buffer快,但它的创建、销毁比普通Buffer慢。

因此直接内存使用于需要大内存空间且频繁访问的场合,不适用于频繁申请释放内存的场合。

class DirectMemory {

// 分配堆内存
public static void bufferAccess() {
    long startTime = System.currentTimeMillis();
    ByteBuffer b = ByteBuffer.allocate(500);
    for (int i = 0; i < 1000000; 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("access_nondirect:" + (endTime - startTime));
}

// 直接分配内存
public static void directAccess() {
    long startTime = System.currentTimeMillis();
    ByteBuffer b = ByteBuffer.allocateDirect(500);
    for (int i = 0; i < 1000000; 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("access_direct:" + (endTime - startTime));
}

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

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

public static void main(String args[]) {
    System.out.println("访问性能测试:");
    bufferAccess();
    directAccess();

    System.out.println();

    System.out.println("分配性能测试:");
    bufferAllocate();
    directAllocate();
}

}

结果:

访问性能测试:
access_nondirect:157
access_direct:134

分配性能测试:
allocate_nondirect:231
allocate_direct:613

转自https://www.cnblogs.com/z-sm/p/6235157.html?utm_source=itdadao&utm_medium=referral

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值