Alex Rivera | Logout

is there a performance hit when using enum.values() vs. String arrays?

Asked 2010-03-15T09:42:40.353
30

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();
}

Clarifications:

  • I'm concerned with a hidden cost related to enumerating values() repeatedly (e.g. inside paint() methods).
  • I can now see that all my scenarios include some int => enum conversion - which is not Java's way.

What is the actual price of extracting the values() array? Is it even an issue?

Android developers

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

Edit
Report

1 Answer

0

As a rule of thumb : before thinking about optimizing, have you any clue that this code could slow down your application ?

Now, the facts.

enum are, for a large part, syntactic sugar scattered across the compilation process. As a consequence, the values method, defined for an enum class, returns a static collection (that's to say loaded at class initialization) with performances that can be considered as roughly equivalent to an array one.

answered 2010-03-15T09:48:11.577

Your Answer