Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin enum class in Android performance

Tags:

In Java we are told to strictly avoid using enums on Android because they take up twice the memory.

Does this apply to enum class in Kotlin aswell? Will a Kotlin enum be compiled into a Java enum?

like image 657
Arbitur Avatar asked Jun 03 '17 22:06

Arbitur


People also ask

Why is enum faster?

Enum values will take more memory compared to an int constant. Adding a single enum will increase the size of the final DEX file approximately 13x when to an integer constant. This is because each value in an enum class is treated as an object, and each value will take some heap memory to reference the object.

Why you should not use enum?

When ENUM type has a long list of values. ENUM types should not be used if you cannot limit a set of possible values to a few elements.

Is enum fast?

Casting from int to an enum is extremely cheap... it'll be faster than a dictionary lookup. Basically it's a no-op, just copying the bits into a location with a different notional type. Parsing a string into an enum value will be somewhat slower.

What is enum class in Android?

Enum in java is a data type that contains fixed set of constants. When we required predefined set of values which represents some kind of data, we use ENUM. We always use Enums when a variable can only take one out of a small set of possible values.


2 Answers

It would appear so, yes.

I created this in Kotlin:

enum class Thingies {     Red,     Green,     Blue } 

And decompiled it with javap -v, and here is the header:

public final class Thingies extends java.lang.Enum<Thingies> minor version: 0 major version: 52 flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM 

Bottom line: they are identical, so you probably have to treat them the same way.

like image 104
Todd Avatar answered Sep 18 '22 19:09

Todd


They are exactly the same thing, a Kotlin Enum is a Java JVM Enum.

like image 40
Jayson Minard Avatar answered Sep 17 '22 19:09

Jayson Minard