从 java 1.4 开始引入直接内存。新的 I/O (NIO) 类引入了一种基于通道和缓冲区执行 I/O 的新方法。NIO 添加了对直接 ByteBuffers 的支持,它可以直接传递到本机内存而不是 Java 堆。在某些情况下使它们显着更快,因为它们可以避免在 Java 堆和本机堆之间复制数据。
我一直不明白我们为什么要使用直接内存。有人可以帮忙举个例子吗?
import java.io.UnsupportedEncodingException;
public class TestChar {
public static void main(String[] args) throws UnsupportedEncodingException {
String cnStr = "?";
String enStr = "a";
byte[] cnBytes = cnStr.getBytes("UTF-8");
byte[] enBytes = enStr.getBytes("UTF-8");
System.out.println("bytes size of Chinese?" + cnBytes.length);
System.out.println("bytes size of English?" + enBytes.length);
// in java, char takes two bytes, the question is:
char cnc = '?'; // will '?‘ take two or three bytes ?
char enc = 'a'; // will 'a' take one or two bytes ?
}
} …Run Code Online (Sandbox Code Playgroud)