Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do most JVMs allocate memory for unused methods?

Say we have the following classes:

class DoubleOhSeven {
  public static void doSomethingClassy();
  public static void neverDoThisClassy();
}

class Dude {
  public void doSomething();
  public void neverDoThis();
}

public class Party {
  public static void main(String[] args){
    DoubleOhSeven.doSomething();
    Dude guy = new Dude;
    guy.doSomething();
  }
}

Of course, all the methods will be compiled into their respective .class: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?

like image 784
fny Avatar asked Nov 24 '12 08:11

fny


1 Answers

The unused methods are still there occupying memory as part of the class / object, even if they're not directly called.

If they were optimised away, then that would make reflective calls on these methods impossible.

One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called.

Unused inherited methods would be exactly the same.

like image 116
Michael Berry Avatar answered Nov 01 '22 20:11

Michael Berry