|
Implementation of 'sizeof'. It is very hard to get reasonable estimations of how much memory your
structures take, this class it trying it any way. Often it's quite a heavy operation, so don't
use it too much.
A count of the byte size of an object is done recursively and for every count a SizeOf instance
must be instantiated. The static
SizeOf.getByteSize(Object) does that for you.
The core of the SizeOf object is then
SizeOf.sizeof(Object) plus a (private) 'countedObjects'
collection. The sizeof method returns the size the given Object would increase the size of this
countedObjects administration. This means that it returns 0 if the Object was already measured by the SizeOf
instance.
This means that it can be tricky to interpret the results of sizeof. The basic rule is that you
should take the size of a lot of similar objects with the same SizeOf instance, and take the
average.
A good example is
org.mmbase.module.core.MMObjectNode . The first one counted will also
count a
org.mmbase.module.core.MMObjectBuilder object - because that is linked to it, so
its memory is also taken (indirectly) - and will therefor give an unexpectedly large value like 20
kb or so. The second MMObjectNode, of the same type, that you'd count would however give a much
better estimation of the memory used by one Node in MMBase. The MMObjectBuilder is not counted
any more in this second Object, because it was already counted because of the first one.
For every individual entity there are several strategies for guessing the size.
- For atomic types (boolean, byte, char, short, int, long, float, double) a constant value is
returned
- If the entity implements
SizeMeasurable it uses
SizeMeasurable.getByteSize(SizeOf)
- For a limited number of known classes, a reasonable guess is done. E.g. if it is a
java.util.Collection it will simply sum the results of sizeof of its elements, and for a String
it will return getBytes().length().
- If all that fails, reflection will be used to sum the results of sizeof of all readable
members.
Don't forget to dereference or clear the SizeOf after use, otherwise it itself is a memory leak.
author: Michiel Meeuwissen since: MMBase-1.6 version: $Id: SizeOf.java,v 1.20 2007/02/25 17:56:58 nklasens Exp $ |