用Java计算对象的大小 [英] Calculate size of Object in Java
问题描述
我想记录一个对象为一个项目占用了多少内存(希望以字节为单位)(我正在比较数据结构的大小),似乎在 Java 中没有方法可以做到这一点.据说,C/C++ 有 sizeOf()
方法,但这在 Java 中是不存在的.我尝试在创建对象之前和之后使用 Runtime.getRuntime().freeMemory()
记录 JVM 中的空闲内存,然后记录差异,但它只会给出 0 或 131304,而在之间,而不考虑结构中的元素数量.请帮忙!
I want to record how much memory (in bytes, hopefully) an object takes up for a project (I'm comparing sizes of data structures) and it seems like there is no method to do this in Java. Supposedly, C/C++ has sizeOf()
method, but this is nonexistant in Java. I tried recording the free memory in the JVM with Runtime.getRuntime().freeMemory()
before and after creating the object and then recording the difference, but it would only give 0 or 131304, and nothing in between, regardless of the number of elements in the structure. Help please!
推荐答案
您可以使用 java.lang.instrumentation
包.
You can use the java.lang.instrumentation
package.
它有一个方法可用于获取对象大小的实现特定近似值,以及与对象相关的开销.
It has a method that can be used to get the implementation specific approximation of object size, as well as overhead associated with the object.
谢尔盖链接的答案有一个很好的例子,我会在这里重新发布,但你应该已经从他的评论中看到了:
The answer that Sergey linked has a great example, which I'll repost here, but you should have already looked at from his comment:
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
使用getObjectSize
:
public class C {
private int x;
private int y;
public static void main(String [] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
}
}
这篇关于用Java计算对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!