Does class without data member have memory footprint in java?
My question is related to memory footprint in java for class without data member. Suppose in java I have a class which doesn't have data member and it only contains methods. So if I am creating instance of particular class the开发者_如何学Gon does it occupies memory in primary memory except object reference memory ?
Ultimately, every Java object know its class and has a synchronization primitive optionally attached to it (though this
can be synthetic). That's two references which it is difficult to make a java.lang.Object
instance do without. Everything else derives from that class, so you've got a floor for costs which worked out to be at least 8 bytes in Java 1.3.1. A profiler will tell you current costs if you really need them.
Yes, it does, because at minimum even an "empty" object has a pointer to its type information.
Let's be clear. References TO your object will, of course, take space. But your object will also take space for its 'this' pointer (i.e. so you can distinguish different instances) and also for the fields of any superclasses - e.g. Object - and finally whatever overhead the heap's internal datastructures have.
Benchmarking memory is difficult because of various sources of interference (growing heap, GC), but it is still worth a try:
public static void main(String[] args)
{
final int n = 1000000;
final Runtime runtime = Runtime.getRuntime();
final Object[] objects = new Object[n];
final long memory0 = runtime.totalMemory() - runtime.freeMemory();
for (int i = 0; i < objects.length; i++)
{
objects[i] = new Object();
}
final long memory1 = runtime.totalMemory() - runtime.freeMemory();
final long memory = memory1 - memory0;
System.out.printf(
"%s %s\n",
System.getProperty("java.vm.name"),
System.getProperty("java.vm.version"));
System.out.printf("%d %d %.1f\n", n, memory, 1.0 * memory / n);
}
Java HotSpot(TM) Server VM 14.3-b01 1000000 8000336 8.0
精彩评论