私有内部类 java,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(){}

}

versus

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

}

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值