在 Java NIO 中,ByteBuffer 可以是直接記憶體(非堆記憶體),也可以是非直接記憶體(堆記憶體)。兩者在 IO 效能上有明顯差異,本文透過官方文檔說明與實測程式碼來對比。
官方文檔描述如下:
A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.
也就是說,對於直接記憶體,JVM 會盡量直接在其上進行本地 IO 操作,避免每次都把內容複製到(或從)一個中間緩衝區;而非直接記憶體(堆內記憶體)的資料若要作 IO,會先複製到直接記憶體,再由本地 IO 處理。
從資料流角度看,非直接記憶體的鏈路是:
本地IO --> 直接記憶體 --> 非直接記憶體 --> 直接記憶體 --> 本地IO
而直接記憶體是:
本地IO --> 直接記憶體 --> 本地IO
很明顯,在處理大量資料傳輸(如網路發送大量資料)時,直接記憶體效率更高。
不過別高興得太早。文檔也指出,直接記憶體以 allocateDirect 建立,其分配與釋放成本比非直接記憶體更高,但這部分資料位於 JVM 之外,不佔用應用堆記憶體。因此,當你有大量且長生命周期的資料要緩存時,比較適合使用直接記憶體;一般情況下,若不能帶來明顯效能提升,仍建議直接用堆內記憶體。
綜合官方文檔與資料,直接記憶體適合:一是很大的資料需要存儲且生命周期很長;二是頻繁的 IO 操作,例如網路並發場景。
用一段簡單程式碼測試申請記憶體空間的速度:
int time = 10000000;
Date begin = new Date();
for (int i = 0; i < time; i++) {
ByteBuffer buffer = ByteBuffer.allocate(2);
}
Date end = new Date();
System.out.println(end.getTime() - begin.getTime());
begin = new Date();
for (int i = 0; i < time; i++) {
ByteBuffer buffer = ByteBuffer.allocateDirect(2);
}
end = new Date();
System.out.println(end.getTime() - begin.getTime());
結果顯示,在資料量提升時,直接記憶體相比非直接記憶體的申請有十分明顯的效能差距——allocateDirect 的分配成本遠高於 allocate。
再寫一段程式碼測試讀寫速度:
int time = 1000;
Date begin = new Date();
ByteBuffer buffer = ByteBuffer.allocate(2 * time);
for (int i = 0; i < time; i++) {
buffer.putChar('a');
}
buffer.flip();
for (int i = 0; i < time; i++) {
buffer.getChar();
}
Date end = new Date();
System.out.println(end.getTime() - begin.getTime());
begin = new Date();
ByteBuffer buffer2 = ByteBuffer.allocateDirect(2 * time);
for (int i = 0; i < time; i++) {
buffer2.putChar('a');
}
buffer2.flip();
for (int i = 0; i < time; i++) {
buffer2.getChar();
}
end = new Date();
System.out.println(end.getTime() - begin.getTime());
可以看到,在直接的 IO 操作上,直接記憶體展現出明顯的優勢。綜合兩組測試:申請成本上堆內記憶體更划算,而實際 IO 讀寫則是直接記憶體更高效——這正是選擇時需要權衡的關鍵。