How to get amount of serialized bytes representing a Java object?

Viewed 21828

What syntax would I use to get the number of bytes representing a string and compare them to the number of bytes representing an ArrayList holding that string, for example?

I am using a multi-agent agent system to send objects via messages and I want to keep track of how much space each message takes up. The method doesn't have to be dead-on accurate, as long as it scales proportionally to the actual size of the object. E.g. a Vector of strings of length 4 will report as smaller than a Vector of strings of length 5.

6 Answers

You can check the size of object after serialization process using Apache Commons as follows:

    // Create serialize objects.
    final List<String> src = new ArrayList<String>();
    src.add("awsome");
    src.add("stack");
    src.add("overflow");

    System.out.println(
            "Size after serialization:" + SerializationUtils.serialize((Serializable) src).length);

Output :

Size after serialization:86
Related