Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does having more methods in a class mean that object uses more memory at runtime

Tags:

java

Say I have one class ClassBig with 100 methods inside, and a second with only 10 methods ClassSmall

When I have objects at runtime


ClassBig big = new ClassBig();
ClassSmall small = new ClassSmall();

Does the larger class take up more memory space?

If both classes contained an identical method, does the larger class take longer to execute it?

like image 697
Richard Taylor Avatar asked May 29 '10 16:05

Richard Taylor


People also ask

Do functions use more memory?

Yes, creating functions uses more memory.

What is the maximum number of methods a class can have?

The number of methods that may be declared by a class or interface is limited to 65535 by the size of the methods_count item of the ClassFile structure (§4.1).

How much memory does a class object occupy?

The class takes up at least 8 bytes. So, if you say new Object(); you will allocate 8 bytes on the heap. Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes!

Do classes take up memory?

In general a class or struct is a concept and does not occupy variable (data) space, but it does take up memory in the compiler's memory.


1 Answers

The in-memory representation of an instance of a class is mainly just its internal state plus a pointer to an in-memory representation of the class itself. The internal representation of an instance method has one more argument than you specified in the class definition - the implicit this reference. This is how we can store only one copy of the instance method, rather than a new copy for every instance.

So a class with more methods will take up more memory than a class with less methods (the code has to go somewhere), but an instance of a class with more methods will use the same amount of memory, assuming the classes have the same data members.

Execution time will not be affected by the number of other methods in the class.

like image 62
danben Avatar answered Oct 20 '22 14:10

danben