如何在不实际序列化的情况下估计Java中对象的序列化大小? [英] How to estimate the serialization size of objects in Java without actually serializing them?

查看:306
本文介绍了如何在不实际序列化的情况下估计Java中对象的序列化大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要增强群集中的消息传递,重要的是要在运行时了解消息的大小(我应该更喜欢处理本地消息还是远程消息)。

To enhance messaging in a cluster, it's important to know at runtime about how big a message is (should I prefer processing local or remote).

我可以找到有关基于java检测估计对象内存大小的框架。我测试了classmexer,它没有接近序列化大小和sourceforge SizeOf。

I could just find frameworks about estimating the object memory size based on java instrumentation. I've tested classmexer, which didn't come close to the serialization size and sourceforge SizeOf.

在一个小的测试用例中,SizeOf错误大约10%,比序列化快10倍。 (仍然瞬态完全破坏了估计,因为例如ArrayList是瞬态的,但是被序列化为数组,修补SizeOf并不容易。但我可以忍受这种情况。)

In a small testcase, SizeOf was around 10% wrong and 10x faster than serialization. (Still transient breaks the estimation completely and since e.g. ArrayList is transient but is serialized as an Array, it's not easy to patch SizeOf. But I could live with that)

On另一方面,10%的误差和10%的误差似乎不太好。我有什么想法可以做得更好吗?

On the other hand, 10x faster with 10% error doesn't seem very good. Any ideas how I could do better?

更新:我还测试了ObjectSize( http://sourceforge.net/projects/objectsize-java )。结果似乎对非继承对象有好处:(

Update: I also tested ObjectSize (http://sourceforge.net/projects/objectsize-java). Results seem just good for non-inheritating objects :(

推荐答案

类在运行时获取的大小不一定有任何影响你提到的例子是瞬态字段。其他例子包括对象何时实现Externalizable并自己处理序列化。

The size a class takes at runtime doesn't necessarily have any bearing on it's size in memory. The example you've mentioned is transient fields. Other examples include when objects implement Externalizable and handle serialization themselves.

如果一个对象实现Externalizable或提供 readObject() / writeObject()那么最好的办法是将对象序列化到内存缓冲区以找出它不会很快,但它会准确。

If an object implements Externalizable or provides readObject()/writeObject() then your best bet is to serialize the object to a memory buffer to find out the size. It's not going to be fast, but it will be accurate.

如果一个对象使用默认序列化,那么你可以修改SizeOf以考虑瞬态字段。

If an object is using the default serialization, then you could amend SizeOf to take into account transient fields.

序列化许多相同类型的对象后,您可以为该类型构建一个序列化配置文件,将序列化大小与SizeOf的运行时大小相关联这将允许你估计ser快速确定大小(使用SizeOf),然后将其与运行时大小相关联,以获得比SizeOf提供的结果更准确的结果。

After serializing many of the same types of objects, you may be able to build up a "serialization profile" for that type that correlates serialized size with runtime size from SizeOf. This will allow you then to estimate the serialized size quickly (using SizeOf) and then correlate this to runtime size, to arrive at a more accurate result than that provided by SizeOf.

这篇关于如何在不实际序列化的情况下估计Java中对象的序列化大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆