对于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
可以看到在内存空间申请上,直接内存毫无优势。
如果内存空间本身需要频繁申请,则不适合使用直接内存。