我做了一個小的基準測試,發現ObjectOutputStream.writeObject
快於ObjectOutputStream.write(byte[] bytes)
,但我似乎無法找到一個可能的解釋是引擎蓋下,writeObject
將調用ObjectOutputStream.write(byte[] bytes)
間接爲什麼ObjectOutputStream.writeObject在寫入字節數組時比寫入字節更快?
測試代碼
public static void main(String[] args) throws Exception {
byte[] bytes = new byte[10000];
for (int i = 0; i < 10000; ++i) {
bytes[i] = (byte) (i % 256);
}
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
try(ObjectOutputStream ostream2 = new ObjectOutputStream(out2)) {
for (int i = 0; i < 10000; ++i) {
ostream2.writeInt(bytes.length);
ostream2.write(bytes, 0, bytes.length);
}
out2.reset();
long start = System.nanoTime();
for (int i = 0; i < 10000; ++i) {
ostream2.writeInt(bytes.length);
ostream2.write(bytes, 0, bytes.length);
}
long end = System.nanoTime();
System.out.println("write byte[] took: " + ((end - start)/1000) + " micros");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try(ObjectOutputStream ostream = new ObjectOutputStream(out)) {
for (int i = 0; i < 10000; ++i) {
ostream.writeObject(bytes);
}
out.reset();
long start = System.nanoTime();
for (int i = 0; i < 10000; ++i) {
ostream.writeObject(bytes);
}
long end = System.nanoTime();
System.out.println("writeObject took: " + ((end - start)/1000) + " micros");
}
}
輸出
寫字節[]了:15445萬分之一
的writeObject了:3111萬分之一
事實上,你是正確的。我將代碼替換爲每次都有一個新數組,寫入字節數組現在比writeObject快。我完全忘記了writeObject所做的緩存 –