I was recently introduced to IntDef and StringDef interfaces by a co worker. I was using enums
to maintain a list of constants for some purpose and he suggested me to use these interfaces. I went ahead to read more on that and would be sharing here what I learned.
So, it turns out that enums often require more than twice as much memory as static constants
(quoted from andev docs). They are class objects, so :
- A single reference to an enum constant occupies
4 bytes
- Every enum occupies space that is the sum of all its fields’ sizes and overhead of an object
- the class itself occupies some space.
Whereas constants require fixed space, 4 bytes
in case of an int constant and (num of chars) * 1
bytes in a string constant.
That said, we can replace enums with constants only in cases where we are just using them as constants. In cases where we are
- storing more (or complex data) data in enums, or
- using method overloading (every enum constant can have it’s own implementation of a method)
we’ll have to go with enums.
Now, I’ll be explaining how to use these interfaces.
We declare them as following :
@StringDef({NotificationAction.DISPLAYED, NotificationAction.CONTENT_CLICKED,
NotificationAction.ACTION_CLICKED, NotificationAction.DISMISSED})
@Retention(RetentionPolicy.SOURCE)
public @interface NotificationAction {
String DISPLAYED = "Displayed";
String CONTENT_CLICKED = "ContentClicked";
String ACTION_CLICKED = "ActionClicked";
String DISMISSED = "Dismissed";
}
That’s it ! Now you can directly use them for annotating fields or method parameters in your code.
Fields :
@NotificationAction String action;
action = "dummy" // doesn't work
action = NotificationAction.DISPLAYED; // works
Methods :
public void actOnAction(@NotificationAction action){}
actOnAction("dummy") // doesn't work
actOnAction(NotificationAction.DISMISSED) // works
This way, it also makes it convenient to allow only certain values at these places.
It won’t improve your app’s performance by a significant bit but yeah, small things like this do count.
Let me know in case of any doubts.
Cheers !
Ref : http://stackoverflow.com/questions/29183904/should-i-strictly-avoid-using-enums-on-android
Comments
Post a Comment