Calculate memory of a Map Entry

后端 未结 2 1178
花落未央
花落未央 2021-01-14 21:09

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). Do

2条回答
  •  [愿得一人]
    2021-01-14 21:59

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

提交回复
热议问题