3

I know that if a class is declared as being final, then its methods are effectively unable to be overridden, since it takes a sublass to override them in the first place. That being said, I'm wondering if this is still completely the same as going through and typing out "final " in front of every method in that class.

The reason I'm asking this is that making methods final supposedly can cause some of them to run faster; what I'm wondering is whether this speed-up benefit is automatically equally present for all methods within a class that's been declared final, or whether you would have to explicitly make the methods final to derive this benefit.

Thanks!

Panzercrisis
  • 4,590
  • 6
  • 46
  • 85

1 Answers1

3

You can't extend a final class, so you can't override its methods. It doesn't really make sense to talk about the methods being final or not.

The theoretical speed increase for final methods is because the compiler can inline the functions in situations where it makes sense. It's hard to predict exactly when the compiler will do that, and mostly you won't notice the difference. It isn't documented (or not to my knowledge) but I imagine the heuristic will be based on the function being short and if it's used in a loop. In that situation, the overhead of the function wrapper will become significant compared to the code that it contains.

Note: inlining isn't possible for functions that use the arguments object.

In practice, you mostly won't notice the speed difference. But if you can construct a case where it can be measured, you can easily test by making the class final instead of the method.

Edit: FWIW, I tried this and couldn't measure a difference between using final on a method and not using it. Using final on the class was the same too. This SO answer reaches the same conclusion.

Community
  • 1
  • 1
Peter Hall
  • 53,120
  • 14
  • 139
  • 204