Home

Thursday 4 August 2016

Android ‘Enums’: Good or Bad ?

While making Android apps there is a time when every developer wonders the efficiency of ‘Java Enums’ in their Android application. Well before getting into it’s usability let’s see how Enums(short for ‘Enumeration’)works:
As written by Oracle, ‘An enum type is a special data type that enables for a variable to be a set of predefined constants.’ What this means is, the variable is assigned a constant value within a set of values within that Enum type. Let’s see an example:


public enum Snacks {
  NACHOS,
  FRIES,
  COOKIES;
}
So now each item is a part of the enum set Snacks with a static constantvalue but how to be really sure? Let’s do some ‘hacky’ stuff!
Compiling the above enum Snacks:


javac Snacks.java
and disassembling resulting class file with javap:


javap Snacks.class
gives the following:


public final class Snacks extends java.lang.Enum<Snacks>{
    public static final Snacks NACHOS;
    public static final Snacks FRIES;
    public static final Snacks COOKIES;
    public static Snacks[] values(); 
    public static Snacks valueOf(java.lang.String); 
    static {}; 
}
Hence we see that all the variables are static and the static variables takes memory irrespective if they are used or not and are not collected by Java Garbage Collector unless the respective class is dropped as they have scope across the entire program.
So static variable in your Android app, looks ugly already but statics are not always bad. What? How? To use any general variable we need to create an object of it’s class, but if that object is created multiple times, the Garbage Collector has to collect it again and again, hence it’s better to use Enums. If there is no such condition then you must avoid enums as much as possible.

No comments:

Post a Comment