I'm using enumerations to replace String
constants in my java app (JRE 1.5).
Is there a performance hit when I treat the enum as a static array of names in a method that is called constantly (e.g. when rendering the UI)?
My code looks a bit like this:
public String getValue(int col) { return ColumnValues.values()[col].toString(); }
values()
repeatedly (e.g. inside paint() methods).int
=> enum
conversion - which is not Java's way.What is the actual price of extracting the values()
array? Is it even an issue?
Read Simon Langhoff's answer below, which has pointed out earlier by Geeks On Hugs in the accepted answer's comments. Enum.values()
must do a defensive copy
Comparisons of enums usually are faster than comparisons of strings. Enumerators have the size of the underlying integral type, while strings can be many characters long.
They are type safe and comparing them is faster than comparing Strings. Show activity on this post. If your set of parameters is limited and known at compile time, use enum . If your set of parameters is open and unkown at compile time, use strings.
The main difference is that an array is a value and an enum is a type. And One main difference we can say that an array is a collection of other values (that is it contains other values, you can iterate through them or access individual ones by index), whereas an enum value is simply one atomic value.
Enums add at least 2x more bytes to the total APK size than plain constants and can use approximately 5-10xmore RAM than equivalent constants. So if you'd like your app to be memory- and performance-efficient, try to avoid enums in your code.
For enums, in order to maintain immutability, they clone the backing array every time you call the Values() method. This means that it will have a performance impact. How much depends on your specific scenario.
I have been monitoring my own Android app and found out that this simple call used 13.4% CPU time! in my specific case.
In order to avoid cloning the values array, I decided to simple cache the values as a private field and then loop through those values whenever needed:
private final static Protocol[] values = Protocol.values();
After this small optimisation my method call only hogged a negligible 0.0% CPU time
In my use case, this was a welcome optimisation, however, it is important to note that using this approach is a tradeoff of mutability of your enum. Who knows what people might put into your values array once you give them a reference to it!?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With