STiGMa
STiGMa

Reputation: 946

Calculate memory of a Map Entry

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.

Upvotes: 3

Views: 1499

Answers (2)

lance-java
lance-java

Reputation: 27976

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;
}

Upvotes: 1

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

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());

Upvotes: 1

Related Questions