如何测试Java中对象引用使用了多少字节?
我想测试我正在使用的 Java VM 中对象引用使用了多少字节。你们知道如何测试这个吗?
谢谢!
I would like to test how many bytes an object reference use in the Java VM that I'm using. Do you guys know how to test this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从字面上看,在大多数 JVM 上,32 位 JVM 上的所有引用都占用 4 个字节,在一个 64 位 JVM 上,引用占用 8 个字节,除非使用了 -XX:+UseCompressedOops,在这种情况下,它占用 4 个字节。
我假设您问如何知道对象占用了多少空间。您可以使用 Instrumentation(不是一件简单的事情),但这只会给您带来浅层深度。 Java 倾向于分解许多对象,而 C++ 可能是单个结构,因此它没有那么有用。
但是,如果您有内存问题,我建议您使用内存分析器。这将为您提供浅层和深层空间物体的使用情况,并为您提供整个系统的图片。这通常更有用,因为您可以从最大的消费者开始并优化它们,即使您已经开发 Java 十年+,您也只会猜测哪里是最佳优化位置,除非您有硬数据。
如果您不想使用探查器,则获取对象大小的另一种方法是分配一个大数组并查看消耗了多少内存。您必须多次执行此操作才能很好地了解平均大小是多少。我会将年轻空间设置得非常高,以避免 GC 混淆您的结果,例如
-XX:NewSize=1g
Taking the question literally, on most JVMs, all references on 32-bit JVMs take 4 bytes, one 64-bit JVMs, a reference takes 8 bytes unless -XX:+UseCompressedOops has been used, in which case it takes 4-bytes.
I assume you are asking how to tell how much space an Object occupies. You can use Instrumentation (not a simple matter) but this will only give you a shallow depth. Java tends you break into many objects something which is C++ might be a single structure so it is not as useful.
However, ifyou have a memory issue, I suggest you a memory profiler. This will give you the shallow and deep space objects use and give you a picture across the whole system. This is often more useful as you can start with the biggest consumers and optimise those as even if you have been developing Java for ten years+ you will only be guessing where is the best place to optimise unless you have hard data.
Another way to get the object size if you don't want to use a profiler is to allocate a large array and see how much memory is consumed, You have to do this many times to get a good idea what the average size is. I would set the young space very high to avoid GCs confusing your results e.g.
-XX:NewSize=1g
不同 JVM 的大小可能有所不同,但 "Sizeof for Java” 说
It can differ from JVM to JVM but "Sizeof for Java" says
如果您需要相当准确,请查看仪器框架。
If you need to be fairly accurate, check out the Instrumentation framework.
这个是我使用的。一定会喜欢那些 16 字节引用!
alphaworks.ibm.heapanalyzer
This one is the one I use. Got to love those 16-byte references !
alphaworks.ibm.heapanalyzer