Search code examples
javamethodsheap-memoryclassloader

Size of Objects in Java Heap w/ Regards to Methods


I know about primitives and objects living on the heap, but how does the number of methods effect heap size of the object?

For example:

public class A {
    int x;
    public getX() { return x; }
}

public class B {
    int x;

    public getX() { return x; }
    public getXString() { return String.valueOf(x); }
    public doMoreInterestingStuff() { return x * 42; }
    //etc
}

When instantiated, both objects live on the heap, both have memory allocated to their primitive x, but is B allocated more heap space due to having more method signatures? Or are those ONLY on the permGen space? In this example its trivial, but when there are 100,000+ of these objects in memory at any given time I imagine it could add up.


Solution

  • how does the number of methods effect heap size of the object?

    It doesn't. It has no impact on the per-object size, and indeed it would have no need to - it's not like each object of that type has different methods.

    Obviously the extra methods take up memory "somewhere" (associated with the class, basically) but it's not on a per object basis.