1, disadvantage: The cost of creating and releasing direct buffer is higher than the heap buffer;
2. Difference: Direct buffer is not allocated on the heap, it is not managed directly by GC (but the Java object of direct buffer is managed by GC, as long as the GC reclaims its Java object, the operating system releases the direct The space requested by buffer), it seems to give the impression that it is "kernel buffers (buffer in kernel)". The heap buffer is allocated on the heap, or we can simply understand that the heap buffer is a form of encapsulation of the byte[] array and view the Java source code implementation, as is the case with heap buffer.
3, Advantage: When we write a direct buffer to the channel, it is like the "kernel buffer" content directly written to the channel, so obviously faster, reduce the data copy (because our usual read/write are needed in i/ o the "kernel buffer" between the device and the application space. When we write a heap buffer to the channel, the underlying implementation actually constructs a temporary direct buffer, and then copies the contents of the heap buffer to this temporary direct buffer, and then the direct Buffer to write it out. Of course, if we call the Write method multiple times and write a heap Buffer to the channel, the underlying implementation can reuse the temporary direct buffer, so that the performance is not affected by the frequent creation and destruction of direct buffer.
To put it simply, we need to keep three points in mind:
(1) The usual read/write will experience a "kernel buffer" between the I/O device and the application space.
(2) Direct buffer is like a cache on a "kernel buffer" that is not directly managed by the GC, whereas heap buffer is simply the wrapper of the byte[] byte array. Therefore, it is faster to write a direct buffer to a channel than to write a heap buffer to a channel.
(3) Direct buffer is expensive to create and destroy, so it needs to be reused wherever possible .
Direct buffer vs. Heap buffer