Java中的私有内部类是否存在性能开销? [英] Is there a performance overhead to a private inner class in Java?

查看:586
本文介绍了Java中的私有内部类是否存在性能开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有私有方法或字段的内部类时,编译器必须创建合成的包受保护的访问器方法,以允许外部类访问这些私有元素(反之亦然)。

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(){}
 }

 static class A {
      A(){}
 }

注意在两种情况下构造函数是否受包保护,或者是否使类私有更改?

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

推荐答案

您是否尝试过编译它?并比较字节码?这是我的结果。对于:

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(){}
  }
}

以上产生以下* .class文件:

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

现在,如果我移动类文件,删除 private 修饰符,并重新编译,我得到:

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

如果你看一下 VM对类文件的规范,您将看到有一个用于指定访问修饰符的恒定大小的位字段,因此生成的文件大小相同并不奇怪。

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.

我还应该补充说,如果更改内部类被声明为<$ c $,则会略有不同c> static 未被声明 static ,因为它意味着引用外部类的附加字段。与声明内部类 static 相比,这将占用更多的内存,但是为了优化这个内容你会疯了(使用 static 哪里有意义,哪里你需要它是非静态的,把它变成非静态的,但是不要只是为了在这里或那里保存一个内存指针而卷入你的设计。

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).

这篇关于Java中的私有内部类是否存在性能开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆