Why static final int is used in android standard classes avoiding enum?

2

In standart android classes static final int vars is used to represent different flags. For example, View visability flags:

/** @hide */
@IntDef({VISIBLE, INVISIBLE, GONE})
@Retention(RetentionPolicy.SOURCE)
public @interface Visibility {}

/**
 * This view is visible.
 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
 * android:visibility}.
 */
public static final int VISIBLE = 0x00000000;

/**
 * This view is invisible, but it still takes up space for layout purposes.
 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
 * android:visibility}.
 */
public static final int INVISIBLE = 0x00000004;

/**
 * This view is invisible, and it doesn't take any space for layout
 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
 * android:visibility}.
 */
public static final int GONE = 0x00000008;

/**
 * Mask for use with setFlags indicating bits used for visibility.
 * {@hide}
 */
static final int VISIBILITY_MASK = 0x0000000C;

private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};

Why developers avoid using enum in this case?

java
android
enums
asked on Stack Overflow Aug 24, 2016 by answersearcher • edited Sep 26, 2017 by Martin O'Shea

2 Answers

0

They do it mainly for performance, as others have said. The main performance impact is the amount of memory they use.

I feel this is the best resource on the matter (from the horses mouth) https://youtu.be/Hzs6OBcvNQE

I know a video is unusual here on SO but it is the most to the point resource on the matter.

A side point: Though Enums are not performance optimised, most apps done in Android Studio should be fine if they use Progaurd to convert all enums at compile time to static final ints. I do this as I find Enums a little more expressive.

answered on Stack Overflow Aug 24, 2016 by Martin O'Shea • edited Aug 24, 2016 by Martin O'Shea
-2

Because enums are expensive. First, they're strings. That means comparing two is a string compare and not an int compare, which can be many times the cost. Secondly, they're objects. Creating lots of small objects on a device with limited RAM is a great way to go OOM due to fragmentation, and each allocation costs time. As such they're horrible for performance.

Really Java messed up when they designed enums- they should never have been objects or strings. Even server side performance oriented code avoids them in favor of ints.

answered on Stack Overflow Aug 24, 2016 by Gabe Sechan • edited Apr 14, 2019 by (unknown user)

User contributions licensed under CC BY-SA 3.0