3

I have a Map(String, String) and I want to find the memory size of an Entry and the Map in total. I read somewhere that Instrumentation might be useful (Instrumentation). Does anyone have an idea?

Thanks in advance.

STiGMa
  • 906
  • 3
  • 11
  • 24
  • You can do plenty of things with instrumentation, but what's your main goal? A profiler can tell you how much memory a map takes. What are your Map entries? – Kayaman Dec 08 '13 at 20:16
  • Both key and value are strings. The main purpose is to calculate the memory consumption of the Map object while the application is running. – STiGMa Dec 08 '13 at 20:44
  • I am interested in the relative consumption per item for the various map types so I can make the speed vs memory trade off. Each map type has a different per-value overhead. ie: a hash map has a different use per value than a TreeMap, or smallest memory binary search of an array [key,value,key,value, ...] of elements. – peterk Oct 07 '14 at 20:54

2 Answers2

1

Use ObjectOutputStream to write the object to a ByteArrayOutputstream and check the length of the resultant byte array.

Obviously your Map.Entry will need to implement Serializable.

public int getSizeInBytes(Serializable someObject) {
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
    objectOut.writeObject(someObject);
    objectOut.flush();
    return byteOut.toByteArray().length;
}

public int getSizeBits(Serializable someObject) {
    return getSizeInBytes(someObject) * 8;
}
lance-java
  • 25,497
  • 4
  • 59
  • 101
  • Thanks for the advice. That's another possible solution. I'll give it a try to compare the answer to the solution provided above. – STiGMa Dec 09 '13 at 15:16
1

A blank instance of java.util.AbstractMap.SimpleEntry should be 24 bytes for 64-bit JVM and 12 bytes for 32-bit JVM. Here is a technique by @PeterLawrey I found useful, based on MemoryUsageExamplesTest:

System.out.printf("The average memory used by simple entry is %.1f bytes%n", new SizeofUtil() {
    @Override
    protected int create() {
        Map.Entry<String, String> e = new AbstractMap.SimpleEntry<String, String>(null, null);
        return 1;
    }
}.averageBytes());
Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68