Issue
I know that int uses 32 bits. Long uses 64 bits and etc... But, how can we know how much memory our object uses? I have a class like this:
class Utils{
public String getName(Context context){
return "Sambhav"
}
}
Now, how can I know how much memory does this class use?
Solution
You cannot. You can only do some very rough estimates. It depends on the version of your JRE.
- Every instance has a minimum memory footprint for management information like a reference to the defining class, maybe 16 bytes.
- For every instance field, add the "size" of that field, plus some padding if the field type is shorter than the default alignment used in your JRE.
- A class is an instance of the class named
Class
, having a lot of internal fields and data structures, besides the fields declaredstatic
. And it "holds" the bytecode of the methods defined there, as well as any compiled native method versions from the HotSpot Just-In-Time compiler. So it's close to impossible to estimate the memory consumption of adding a new class to a JRE. - A string literal like
"Sambhav"
adds oneString
instance to the constants pool if it isn't already present there. And aString
instance has at least a length field and an array holding the characters. The internal details have changed with various versions of JRE.
Now analyzing your Utils
class snippet:
- You only have the class, no instance. So, add the (unknown) memory footprint of the class to your calculation.
- Your user code needs one
String
literal that's probably not yet present in the constant pool. So, add two instances to your calculation, oneString
instance plus one character-holding array, with the array's footprint of course depending on the string length.
Answered By - Ralf Kleberhoff
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)