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()
So, to answer question 2, yes, all compilers will treat private methods as final . The compiler will not allow any private method to be overridden. Likewise, all compilers will prevent subclasses from overriding final methods.
No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.
private is about accessibility like public or protected or no modifier. final is about modification during inheritance. private methods are not just accessible from the outside of the class. final methods can not be overridden by the child class.
In Java as both private and final methods do not allow the overridden functionality so no use of using both modifiers together with same method.
Adding final
to methods does not improve performance with Sun HotSpot. Where final
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. Adding final
to private methods makes no odds.
As ever, these sort of micro-optimisations are not worth spending time on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With