52

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()
deamon
  • 89,107
  • 111
  • 320
  • 448
  • Private methods are not inherited and hence cannot be overriden. A subclass can contain a method with the same name as a final private method in the superclass. It therefore doesnt make senss to declare a method as private final. – Chetan Kinger Nov 24 '12 at 06:26

6 Answers6

69

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • ... in 99.9% of the time. And you'll know when micro-optimizations do make sense. More importantly, `private final` method declarations make no sense semantically so it only adds confusion where there was none; just `private` should suffice. – Maarten Bodewes May 13 '15 at 08:20
21

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.

Binoj Antony
  • 15,886
  • 25
  • 88
  • 96
8

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.

Chandra Patni
  • 17,347
  • 10
  • 55
  • 65
7

Marking a private method as final does not change anything but it might confuse junior developers looking at your code. Keep it simple.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
4

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:

reevesy
  • 3,452
  • 1
  • 26
  • 23
Doug Porter
  • 7,721
  • 4
  • 40
  • 55
-1

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.

giri
  • 26,773
  • 63
  • 143
  • 176