Differences between allocate and allocatedirect of bytebuffer
In Java, when we want to perform more underlying operations on the data, it is usually in the byte format of the operation data. In this case, we often use the bytebuffer class. Bytebuffer provides two static instance methods:
public static ByteBuffer allocate(int capacity) public static ByteBuffer allocateDirect(int capacity)
Why are two methods available? This is related to the memory usage mechanism of Java.
- The memory overhead produced by the first allocation method is in the JVM,
- The second allocation method generates overhead outside JVM, Which is system-level memory allocation.
When the Java program receives external data, it is first obtained by the system memory, and then copied to the JVM memory for use by the Java program. Therefore, in the second allocation method, you can save the copy operation, which improves the efficiency. However, system-level memory allocation is much time-consuming than JVM memory allocation, so allocatedirect is not always the most efficient. The following is a comparison of the two allocation methods in different capacities:
As shown in the figure, when the volume of data operated is very small, the operation time of the two allocation methods is basically the same. The first method may be faster, but when the volume of data is large, the second method is much larger than the first method.
From: http://blog.sina.com.cn/s/blog_67dc11000101cpsk.html
Differences between allocate and allocatedirect of bytebuffer