为什么序列化Integer会产生太多的开销?

时间:2017-10-30 11:28:19

标签: java serialization

我正在研究Java中的序列化并编写了非常简单的代码:

public class OutputStreamStub extends OutputStream{
    public List<Integer> a = new ArrayList<>();

    @Override
    public void write(int b) throws IOException {
        a.add(b);
    }
}

OutputStreamStub stub = new OutputStreamStub();
ous = new ObjectOutputStream(stub); //stub.a contains 4 bytes now
ous.writeObject(new Integer(12342134));   //stub.a contains 81 bytes now

在4字节整数后,我们得到了81个字节。为什么我们有太多的开销?为什么在创建ObjectOutputStream后会写入4个字节?

1 个答案:

答案 0 :(得分:2)

我有 JDK8 所以当我查看构造函数的来源时:

public ObjectOutputStream(OutputStream out) throws IOException {
    verifySubclass();
    bout = new BlockDataOutputStream(out);
    handles = new HandleTable(10, (float) 3.00);
    subs = new ReplaceTable(10, (float) 3.00);
    enableOverride = false;
    writeStreamHeader();
    bout.setBlockDataMode(true);
    if (extendedDebugInfo) {
        debugInfoStack = new DebugTraceInfoStack();
    } else {
        debugInfoStack = null;
    }
}

您可以看到在调用和初始化writeStreamHeader()之后调用了protected void writeStreamHeader() throws IOException { bout.writeShort(STREAM_MAGIC); // STREAM_MAGIC = 0xaced bout.writeShort(STREAM_VERSION); // STREAM_VERSION = 5 } 。它的实现如下:

<br>

只是附加标题信息。所以我猜这是额外的4个字节来自哪里。