如果你的项目在做内存优化,那么请尝试用注解替代枚举!!!
枚举 在Android开发中通常用于 范围限制和类型安全,可读性比较好。但是基于枚举的原理,它占用的内存过多,因此不推荐使用。
为什么枚举占用内存更高?
举个例子:
public enum Numbers {
One,
Two,
Three;
}
这段代码等效的java代码如下:
public final class Numbers extends Enum
{
public static Numbers[] values()
{
return (Numbers[])$VALUES.clone();
}
public static Numbers valueOf(String name)
{
return (Numbers)Enum.valueOf(com/brycegao/test/Numbers, name);
}
private Numbers(String s, int i)
{
super(s, i);
}
public static final Numbers One;
public static final Numbers Two;
public static final Numbers Three;
private static final Numbers $VALUES[];
static
{
One = new Numbers("One", 0);
Two = new Numbers("Two", 1);
Three = new Numbers("Three", 2);
$VALUES = (new Numbers[] {
One, Two, Three
});
}
}
从代码中可知:枚举值是类对象,而且是静态常量,而一个对象占至少16字节,3个对象就是16✖️3。而如果写成静态常量的形式,就是4✖️3。
使用注解@IntDef和@StringDef
public class Numbers {
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final String STR_ONE = "ONE";
public static final String STR_TWO = "TWO";
public static final String STR_THREE = "THREE";
@IntDef({ONE, TWO, THREE})
@Retention(RetentionPolicy.SOURCE)
public @interface NumbersInt {
}
@StringDef({STR_ONE, STR_TWO, STR_THREE})
@Retention(RetentionPolicy.SOURCE)
public @interface NumbersString {
}
}
注解的这种方式可以修饰成员变量/方法参数等,可以用作参数,也可用于限定范围