我做了一个小型基准测试,发现ObjectOutputStream.writeObjectObjectOutputStream.write(byte[] bytes)快,但是我似乎找不到可能的解释,因为writeObject会间接调用ObjectOutputStream.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");
    }
}


输出量


  写入byte []需要:15445微米
  
  writeObject需要:3111微米

最佳答案

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

关于java - 为什么在写字节数组时ObjectOutputStream.writeObject比写字节快?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32396216/

10-13 03:00