標籤:out print 測試 ted flip 堆記憶體 ini long put
NIO的Buffer提供了一個可以不經過JVM記憶體直接存取系統實體記憶體的類——DirectBuffer。 DirectBuffer類繼承自ByteBuffer,但和普通的ByteBuffer不同,普通的ByteBuffer仍在JVM堆上分配記憶體,其最大記憶體受到最大堆記憶體的限制;而DirectBuffer直接分配在實體記憶體中,並不佔用堆空間,其可申請的最大記憶體受作業系統限制。
直接記憶體的讀寫操作比普通Buffer快,但它的建立、銷毀比普通Buffer慢。
因此直接記憶體使用量於需要大記憶體空間且頻繁訪問的場合,不適用於頻繁申請釋放記憶體的場合。
以下是一些測試:
代碼:
1 public class DirectMemory { 2 // 直接分配記憶體 3 public static void directAccess() { 4 long startTime = System.currentTimeMillis(); 5 ByteBuffer b = ByteBuffer.allocateDirect(500); 6 for (int i = 0; i < 1000000; i++) { 7 for (int j = 0; j < 99; j++) 8 b.putInt(j); 9 b.flip();10 for (int j = 0; j < 99; j++)11 b.getInt();12 b.clear();13 }14 long endTime = System.currentTimeMillis();15 System.out.println("directAccess:" + (endTime - startTime));16 }17 18 // 分配堆記憶體19 public static void bufferAccess() {20 long startTime = System.currentTimeMillis();21 ByteBuffer b = ByteBuffer.allocate(500);22 for (int i = 0; i < 1000000; i++) {23 for (int j = 0; j < 99; j++)24 b.putInt(j);25 b.flip();26 for (int j = 0; j < 99; j++)27 b.getInt();28 b.clear();29 }30 long endTime = System.currentTimeMillis();31 System.out.println("bufferAccess" + (endTime - startTime));32 }33 34 public static void directAllocate() {35 long startTime = System.currentTimeMillis();36 for (int i = 0; i < 1000000; i++) {37 ByteBuffer.allocateDirect(1000);38 }39 long endTime = System.currentTimeMillis();40 System.out.println("directAllocate:" + (endTime - startTime));41 }42 43 public static void bufferAllocate() {44 long startTime = System.currentTimeMillis();45 for (int i = 0; i < 1000000; i++) {46 ByteBuffer.allocate(1000);47 }48 long endTime = System.currentTimeMillis();49 System.out.println("bufferAllocate:" + (endTime - startTime));50 }51 52 public static void main(String args[]) {53 54 bufferAccess();55 directAccess();56 57 System.out.println();58 59 bufferAllocate();60 directAllocate();61 }View Code
結果:
bufferAccess175directAccess:134bufferAllocate:233directAllocate:634
Java直接記憶體與堆記憶體