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

前端 未结 6 621
执笔经年
执笔经年 2021-02-01 20:45

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

6条回答
  •  情书的邮戳
    2021-02-01 21:31

    I don't think you've got much choice but to modify your code so that it measures the message sizes at runtime.

    You could just serialize example objects and capture and measure the serialized size. This has the following problems:

    • You can never be sure that the objects are typical.
    • Various aggregation effects mean that it is hard to deduce the size of a message from the serialized size of its component objects. (For instance, class signatures are only encoded once per serialization.)
    • This approach tells you nothing about the relative frequency of different message types.

    If you can manage this, you will get more accurate results if you can measure the actual messages. This would most likely entail modifying the agent framework to count, measure and (ideally) classify messages into different kinds. The framework might already have hooks for doing this.

    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 larger than a Vector of strings of length 5.

    (I assume that you meant smaller than ...)

    Your example illustrates one of the problems of trying to estimate serialized object sizes. A serialization of a Vector of size 4 could be smaller ... or larger ... that a Vector of size 5. It depends on what the String values are. Additionally, if a message contains two Vector objects, the serialized size occupied by the vectors will be less that sum of the sizes of the two vectors when they are serialized separately.

提交回复
热议问题