静态内部类有性能成本吗?
静态内部类有性能成本吗?或者我应该编写与非内部类相同的静态类?
Is there a performance cost to static inner class? Or should I just write the same static class as a non-inner class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的业务/数据逻辑确定某个类应该是内部类,则将其设为内部类。
如果您遇到性能问题,请进行测量以确定问题所在,然后找出要进行哪些优化。
If your business/data logic determines that a class should be an inner class then make it an inner class.
If you are having performance problems take measurements to determine where the problem is and then work out what optimisations to make.
根据我刚刚运行的测试*,没有任何区别。
输出:
我运行了几次,数字始终相同。
*我假设您询问的是访问外部静态类与内部静态类的成员(例如,调用方法调用)的成本。如果我误解了,这个测试是无关紧要的。
According to this test I just ran*, there's no difference.
Output:
I ran it a few times and the numbers were consistently the same.
*I am assuming you were asking about the cost of accessing members (e.g., invoking method calls) of outer static vs. inner static classes. If I misunderstood, this test is irrelevant.
嵌套类与语义和可见性有关,这些几乎总是比性能重要得多。
除此之外,我非常有信心没有(重要的)性能差异 - 这只是一个具有不同可见性的普通类。也许在类初始化期间或使用反射时存在一些细微的差异,但这应该不重要。
Nesting classes is about semantics and visibility and these are almost always much more important then performance.
Besides that I am quite confident that there is no (important) performance difference - it is just a normal class with different visibility. Maybe there are some subtle difference during class initalization or when using reflection but that should hardly matter.
不,但是如果您使用带有泛型的嵌套类,则会出现一些严重的语义问题。 (尽管其中一些问题是非常积极的,例如内部类如何继承父类的类型参数。)
No, but there are some serious semantic issues if you are using nested classes with generics. (Though some of those issues are quite positive, like how an inner class inherits the parent class's type parameters.)