The NIO buffer provides a class--directbuffer that can directly access the system's physical memory without having to go through the JVM's memory. The Directbuffer class inherits from Bytebuffer, but unlike normal bytebuffer, ordinary bytebuffer still allocates memory on the JVM heap, its maximum memory is limited by the maximum heap memory, and Directbuffer is allocated directly in physical memory. Does not occupy heap space, the maximum amount of memory that can be requested is limited by the operating system.
Direct memory reads and writes faster than normal buffer, but it is created and destroyed slower than normal buffer.
As a result, direct memory is used in situations where large memory space is required and frequent access is not available for applications where memory is frequently requested.
Here are some tests:
Code:
1 Public classDirectmemory {2 //allocating memory directly3 Public Static voiddirectAccess () {4 LongStartTime =System.currenttimemillis ();5Bytebuffer B = Bytebuffer.allocatedirect (500);6 for(inti = 0; i < 1000000; i++) {7 for(intj = 0; J < 99; J + +)8 B.putint (j);9 B.flip ();Ten for(intj = 0; J < 99; J + +) One b.getint (); A b.clear (); - } - LongEndTime =System.currenttimemillis (); theSystem.out.println ("directAccess:" + (EndTime-startTime)); - } - - //Allocating heap Memory + Public Static voidbufferaccess () { - LongStartTime =System.currenttimemillis (); +Bytebuffer B = Bytebuffer.allocate (500); A for(inti = 0; i < 1000000; i++) { at for(intj = 0; J < 99; J + +) - B.putint (j); - B.flip (); - for(intj = 0; J < 99; J + +) - b.getint (); - b.clear (); in } - LongEndTime =System.currenttimemillis (); toSystem.out.println ("bufferaccess" + (EndTime-startTime)); + } - the Public Static voiddirectallocate () { * LongStartTime =System.currenttimemillis (); $ for(inti = 0; i < 1000000; i++) {Panax NotoginsengBytebuffer.allocatedirect (1000); - } the LongEndTime =System.currenttimemillis (); +System.out.println ("Directallocate:" + (EndTime-startTime)); A } the + Public Static voidbufferallocate () { - LongStartTime =System.currenttimemillis (); $ for(inti = 0; i < 1000000; i++) { $Bytebuffer.allocate (1000); - } - LongEndTime =System.currenttimemillis (); theSystem.out.println ("Bufferallocate:" + (EndTime-startTime)); - }Wuyi the Public Static voidMain (String args[]) { - Wu bufferaccess (); - directAccess (); About $ System.out.println (); - - bufferallocate (); - directallocate (); A}
View Code
Results:
bufferaccess175directaccess:134bufferallocate:233directallocate:634
Java Direct Memory vs. heap memory