为什么ObjectOutputStream.writeObject在写字节数组时比写字节更快?

Ade*_*ros 0 java objectoutputstream

我做了一个小的基准测试,发现ObjectOutputStream.writeObject速度比ObjectOutputStream.write(byte[] bytes)我快,但我似乎无法找到可能的解释,因为在引擎盖下,writeObjectObjectOutputStream.write(byte[] bytes)间接调用

测试代码

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

写字节[]花了:15445微

writeObject采取:3111微

use*_*421 6

ObjectOutputStream.writeObject()保存书面对象.如果您已经编写了该对象,它只会将句柄写入同一个对象,而不是整个对象.