将私有方法设为最终方法?
将私有方法设为final有好处吗?这会提高性能吗?
我认为“private final”没有多大意义,因为私有方法不能被重写。因此,方法查找应该像使用 Final 时一样高效。
将私有辅助方法设置为静态(如果可能)会更好吗?
最好用什么?
private Result doSomething()
private final Result doSomething()
private static Result doSomething()
private static final Result doSomething()
Is it beneficial to make private methods final? Would that improve performance?
I think "private final" doesn't make much sense, because a private method cannot be overridden. So the method lookup should be efficient as when using final.
And would it be better to make a private helper method static (when possible)?
What's best to use?
private Result doSomething()
private final Result doSomething()
private static Result doSomething()
private static final Result doSomething()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将私有方法标记为 Final 不会改变任何内容,但可能会让初级开发人员在查看代码时感到困惑。保持简单。
Marking a private method as final does not change anything but it might confuse junior developers looking at your code. Keep it simple.
IBM Developer 的工作原理: Java 理论与实践:这是您的最终答案吗? 文章是一篇关于在 Java 中使用
final
关键字的老文章,但很精彩:The IBM Developer works: Java theory and practice: Is that your final answer? article is an oldie but goodie about using the
final
keyword in Java:通过将方法设置为最终方法,我们无法重写该方法。由于私有方法无法在类外部访问。没有必要将该方法设为最终的和私有的。它可能会影响性能。
By making method final we can not override the method. Since Private methods cant be accessed outside the class. There is no sence of making the method final and private. It may hit the performance.
将
final
添加到方法中不会提高 Sun HotSpot 的性能。在可以添加final
的地方,HotSpot 会注意到该方法永远不会被覆盖,因此对其进行相同的处理。在 Java 中,私有方法是非虚拟的。您无法覆盖它们,即使使用子类可以访问它们的嵌套类也是如此。例如,调用私有方法的指令与调用非私有方法的指令不同。将
final
添加到私有方法中没有任何可能性。与以往一样,这些微观优化不值得花时间。
Adding
final
to methods does not improve performance with Sun HotSpot. Wherefinal
could be added, HotSpot will notice that the method is never overridden and so treat it the same.In Java
private
methods are non-virtual. You can't override them, even using nested classes where they may be accessible to subclasses. For instance methods the instructoin to call privates is different from that used for non-privates. Addingfinal
to private methods makes no odds.As ever, these sort of micro-optimisations are not worth spending time on.
private static Result doSomething()
,如果此方法未使用任何实例变量。无论如何,使它们最终化是没有意义的,因为访问器是私有的。
private static Result doSomething()
, if this method is not using any instance variables.In any case making them final makes no sense since the accessor is private.
不,不会的。私有方法不被继承。因此,将它们定为最终版本是一个有争议的问题。另请注意,您不应为了性能而将方法设为最终方法。 JVM 比这更聪明。这种优化并没有多大用处。你应该根据语义和设计将事物定为最终的、私有的、私有的、受保护的、私有的等。
No. It will not. private methods are not inherited. So making them final is a moot point. Also note that you should not make methods final for performance. JVM is smarter than that. This kind of optimization is not much useful. You should make things final, private, private, protected, private, etc based on the semantics and design.