Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding methods to a Java class boost the memory usage of its instances?

Adding member variables to a class certainly boosts the memory footprint of its instances on the heap, but what about a class's methods?

For example, if I have a class composed of a single StringBuilder, but keep adding dozens of methods to manipulate that StringBuilder, will each instance of that class take up proportionally more memory as I add more methods?

Thanks!

like image 924
Syndog Avatar asked Mar 27 '12 17:03

Syndog


2 Answers

No, adding methods does not increase the footprint of the object, only the footprint of the compiled code. In other words, the per-instance memory cost is zero.

like image 58
Sergey Kalinichenko Avatar answered Nov 15 '22 17:11

Sergey Kalinichenko


The short answer is no, it will not add more memory to each object living in the heap. The only thing that will happen is when the class is first loaded, it will also load this methods.

like image 43
Oscar Gomez Avatar answered Nov 15 '22 16:11

Oscar Gomez