Enums
Garbage Collection
Under the hood, enums are static members of the class, so they don't get garbage collected. They stay in memory for the lifespan of your app. This can be an upside or a downside.
The garbage collection process is expensive in terms of CPU usage. The same is true for object creation, you don't want to create the same objects again and again. So, with enums, you save the cost of garbage collection as well as object creation. This is the upside.
The downside is that the enums stay in memory even when they are not in use, this can keep the memory occupied all the time.
Factors to Consider
You don't need to worry about all this, if you have 100 to 200 enums in your app. But when you have more than that, you have a decision to make whether you should go for enums depending on the facts such as the number of enums, whether they will be in use all the time and the amount of memory allocated to your JVM.
Comparison
The comparison of enum values is faster in the when
expression because under the hood it uses tableswitch
to compare the objects.
Android
In Android, when the optimization is enabled, the Proguard converts the enums that don't have functions and properties to integers. This way, you get the type-safety of the enums at compile-time and the performance of the ints at runtime!
Sealed Classes
Garbage Collection
Sealed classes are just regular classes with the only exception that they need to be extended in the same package and the same compilation unit. So, their performance is equivalent to regular classes.
Objects of the subtypes of the sealed classes get garbage collected like the objects of regular classes. So, you have to bear the cost of garbage collection as well as object creation.
Factors to Consider
When you have the low memory constraints, you may consider using sealed classes instead of enums, if you need thousands of objects. Because the garbage collector can collect the objects when the memory is low and the objects are not in use.
If you use object
declaration for extending the sealed class, the objects act as singletons and they won't be garbage collected, this behaviour is similar to enums. But there is an additional cost of loading the associated classes and keeping them in memory because object
declarations have associated classes with the same names as the objects under the hood.
Comparison
The comparison of sealed class' types is slower in the when
expression because under the hood it uses instanceof
to compare the types. The speed difference between enums and sealed classes, in this case, is very little though. It matters only when you are comparing thousands of constants in a loop.
Android
Proguard doesn't have any integer optimization like enums for sealed classes. So, if you want to have just constants without functions and properties in Android, sticking to enums is a better idea.
That's it! Hope that helps.