APP开发实战145-Enum枚举变量的处理

来源:互联网 发布:游戏程序员面试 编辑:程序博客网 时间:2024/04/30 17:40

Enum枚举变量的处理


1 少用枚举变量,枚举类型 Enum 的内存消耗是静态常量的2倍。

在Google的官方文档中,有如下说明:

Forexample, enums often require more than twice as much memory as static constants.You should strictly avoid using enums on Android.

(https://developer.android.com/topic/performance/memory.html)


2 少用枚举类型,以减少APK的大小。

在Google的官方文档中,有如下说明:

RemoveEnumerations

A single enum can addabout 1.0 to 1.4 KB of size to your app's classes.dex file. Theseadditions can quickly accumulate for complex systems or shared libraries. Ifpossible, consider using the @IntDef annotation and ProGuard tostrip enumerations out and convert them to integers. This type conversionpreserves all of the type safety benefits of enums.

(https://developer.android.com/topic/performance/reduce-apk-size.html#apk-structure

)

Google官方推荐使用@IntDef annotation替代枚举,其实现的具体方式如下:

publicclass Types{

    //声明一个注解为UserTypes

//使用@IntDef修饰UserTypes,参数设置为待枚举的集合

//使用@Retention(RetentionPolicy.SOURCE)指定注解仅存在与源码中,不加入到class文件中

@IntDef({TECHER,STUDENT})

@Retention(RetentionPolicy.SOURCE)

public@interface UserTypes{}

 

//声明必要的int常量

publicstatic final int TECHER = 0;

publicstatic final int STUDENT = 1;

}

用作函数的参数时:

privatevoid setType(@UserTypes int type) {

        mType = type;

}

调用的该函数的时候:

setType(UserTypes. TECHER);

 

用作函数的返回值时:

@ UserTypes

publicint getType() {

    return mType;

}

 

使用ProGuard 处理枚举常量的代码如下:

-optimizationsclass/unboxing/enum

此代码可将枚举类型的变量转换成整型。若确保上述代码生效,需要确proguard配置文件不包含-dontoptimize指令。



0 0