2

According to this SO question and performance benchmarks

We can assume that defining classes as public final class is better for performance.

Should we do the same with Android Activities, as they are mostly not used to subclassing ?

public final class LoginActivity extends Activity { ... }
Community
  • 1
  • 1
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244

2 Answers2

6

It's usually a safe bet to make all your classes either abstract or final.

This way, it's clear whether a class needs to be designed for inheritance.

If you later find out that for some reason you need to inherit from a concrete (non-abstract) class - which is usually a sign that there's a bit of asymmetry in your overall design - you can still remove the final keyword and make sure that your class is fit for inheritance.

So by doing this you eliminate the waste of having to design all your classes for inheritance, and at the same time you get maintainable code with clear intentions.

yeoman
  • 1,671
  • 12
  • 15
  • 1
    And yes, you also allow the jvm to inline calls to methods of a final class when it is used with its concrete type, so - even though my argument about clear intentions is way more important from my personal point of view - you can get better performance. Inlining really is a powerful tool. Another vehicle to get this advantage is using final and / or private methods, as they are also guaranteed never to be overridden. Therefore, do not use non-private non-final methods of a non-final class in performance critical inner loops :-) – yeoman Nov 27 '11 at 09:33
4

I've never seen anyone, including Google, doing this in code. We're told Dalvik VM is highly optimized in itself and it can follow from this that bothering about declaring your Activities final will not result in any noticeable performance increase. One declares a class final usually for reasons other than performance reasons.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • True. I also rarely explicity declare classes as final, as doing so adds visual clutter. It's usually just data immutable structures, mostly generated, where I use final for enforcing immutability by prohibiting possibly mutable derived classes. – yeoman Dec 20 '18 at 22:54