views:

154

answers:

4

Suppose I have a Java class that has 100K worth of method code containing NO variables, but only 20 bytes of attributes.

I instantiate 1000 objects from this class.

Have I consumed 100,000K of memory? Or only 100K + (20bytes * 1000)? Or something else altogether?

+8  A: 

The memory footprint for loading the class itself will approximately correspond to the code size, but the code will not be duplicated for each instance of the class. An instance will only require as much memory as the instance attributes + some overhead for managing the object instance itself.

jarnbjo
A: 

You will have instantiated only the 'variable' part of the objects, so only the attributes (and I guess a few bytes overhead here and there). Your latter guess is the correct one.

Kosi2801
+1  A: 

Here's a general guide to determining the memory usage of objects in Java: http://www.javamex.com/tutorials/memory/object%5Fmemory%5Fusage.shtml

I suspect that the memory usage incurred from method definitions will be a fixed amount, (possibly put into permgen space when the class is loaded) rather than proportional to the number of instances.

Peter
A: 

Try attaching with jvisualvm (in the JDK) and tell us what you see.

Thorbjørn Ravn Andersen