St.Antario
St.Antario

Reputation: 27385

Why is serializing Integer produce too much overhead?

I'm investigating serialization in Java and wrote the very simple code:

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

After the 4 bytes integer we got 81 bytes. Why do we have too much overhead? And why do we have 4 bytes written after creating the ObjectOutputStream?

Upvotes: 1

Views: 98

Answers (1)

Lino
Lino

Reputation: 19926

I have JDK8 so when i look at the source of the constructor:

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;
    }
}

You can see that after some verifying and initializing writeStreamHeader() is invoked. It's implementation looks like this:

protected void writeStreamHeader() throws IOException {
    bout.writeShort(STREAM_MAGIC);   // STREAM_MAGIC = 0xaced
    bout.writeShort(STREAM_VERSION); // STREAM_VERSION = 5
}

Which just appends the header information. So I am guessing that's where the extra 4 bytes come from.

Upvotes: 2

Related Questions