-2

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?

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
  • You need to clarify your question. You don't have an object. You have a static method that returns a `String`. The amount of memory occupied by the code of the `Utils` class is not possible to determine (unless you are prepared to do a huge amount of research and "bookkeeping"), and it is probably irrelevant. – Stephen C May 18 '22 at 06:48
  • Why do you need to know how much memory an instance of this will take ?. In any case, it will depend on the runtime environment. – jr593 May 18 '22 at 06:54

1 Answers1

-1

You can't. 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 declared static. And it "holds" the bytecode of the methods defined there and 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 one String instance to the constants pool if it isn't already present there. And a String 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, one String instance plus one character-holding array, with the array's footprint of course depending on the string length.
Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7