Is there a performance overhead to a private inner class in Java?

Thilo picture Thilo · Feb 10, 2011 · Viewed 8.5k times · Source

When I have inner classes with private methods or fields the compiler has to create synthetic package-protected accessor methods to allow the outer class to access those private elements (and vice-versa).

To avoid that, I usually make all fields and methods and constructors package-protected instead of private.

But how about the visibility of the class itself? Is there an overhead to

 private static class A {
      A(){}
 }

versus

 static class A {
      A(){}
 }

Note that the constructor is package-protected in both cases, or does making the class private change that?

Answer

Michael Aaron Safyan picture Michael Aaron Safyan · Feb 10, 2011

Have you tried compiling it and comparing the byte code? Here are my results. For:

public class Example {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
  private static class A {
    A(){}
  }
}

The above yields the following *.class files:

-rw-r--r--    1 michaelsafyan  staff   238 Feb 10 00:11 Example$A.class
-rw-r--r--    1 michaelsafyan  staff   474 Feb 10 00:11 Example.class

Now, if I move the class files, delete the private modifier, and recompile, I get:

 -rw-r--r--    1 michaelsafyan  staff   238 Feb 10 00:15 Example$A.class
 -rw-r--r--    1 michaelsafyan  staff   474 Feb 10 00:15 Example.class

If you look at the VM Spec on class files, you'll see that there is a constant-sized bit field for specifying the access modifiers, so it should not be any surprise that the generated files are the same size.

In short, your access modifiers won't affect the size of the generated byte code (it also should not have any performance impact, either). You should use the access modifier that makes the most sense.

I should also add that there is a slight difference if you change the inner class from being declared static to not being declared static, as it implies an additional field referencing the outer class. This will take up slightly more memory than if you declared the inner class static, but you'd be insane to optimize for this (use static where it makes sense, and where you need it to be non-static, make it non-static, but don't convolute your design just to save a pointer of memory here or there).