I have a custom collection that stores compressed data.
How can I easily get the size in KB or MB of the collection?
I want to see how efficiently my data is being stored, and the effect of compression on some of the data.
I have a custom collection that stores compressed data.
How can I easily get the size in KB or MB of the collection?
I want to see how efficiently my data is being stored, and the effect of compression on some of the data.
Maybe the easiest way is to count the amount memory (object size) consumed when you add or remove items from your collection, at that time you might now the size of the compressed objects you put on your collection, just add that to the current size. I think this is an alternative from just calculating the whole size every time you need it.
To know the size of an individual object, you can use: http://www.javapractices.com/topic/TopicAction.do?Id=83
That technique basically gets the memory before you create an object and after you create it, with: Runtime.getRuntime().totalMemory()
There are other techniques.
The quick and dirty answer would be:
public static void main(final String[] args) {
System.out.println("Before: " + getUsedMem());
final byte[] bb = new byte[30 * 1024 * 1024]; // 30 MB
System.out.println("After: " + getUsedMem());
}
private static String getUsedMem() {
final long mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
return (mem / 1024) + "KB";
}
However, keep in mind that due to its garbage collector, multi-threading architecture etc., those numbers will not be precise. Especially if you run a GUI along with it. If you stick to a very simple program with no static initializers and no chance for the Garbage Collector to kick in, then you might get it pretty exact.