is Enum.values() a real memory hog ?

According to this article, https://www.javacodegeeks.com/2018/08/memory-hogging-enum-values-method.html

“A recent post on the OpenJDK compiler-dev mailing list titled “about Enum.values() memory allocation” observes that “Enum.values() allocates a significant amount of memory when called in a tight loop as it clones the constant values array.” The poster of that message adds that this “is probably for immutability” and states, “I can understand that.” This message also references a March 2012 message and associated thread on this same mailing list.”

I’ve seen many inner loops in graphics/games engines using the Enum.values() call. I just suspect we should avoid such calls. It seems that escape analisys has little to do here.

I’d imagine escape analysis has lots to do here, myself, as using something in a loop in this way is a pretty sure-fire EA friendly pattern.
Nonetheless… avoiding allocation unfortunately still remains a performance issue in Java. The problem being that the moment you turn your gaze on it using a profiler all of the clever optimisation that might have made it “go away” is removed and it looks terrible. The only way to really see what it’s doing is to look at the output disassembly.

Cas :slight_smile:

Eh, caching values in the enum may be of help in some cases, as the article says.

i.e. in the enum

public Enum TYPE
{

      private static final TYPE[] _values  TYPE.values();

   public static TYPE[] _values()
   {
      return _values;
   }

}

And the use for-loops with the TYPE._values();

Still readable. but using a static, dangerous, not-immutable array

You have to be particularly scared of yourself if you’re worried about writing into your own enum arrays… I’d say you should only really worry about that sort of thing if you’re making public API code. If you’re making some game or other… it’s your code, just remember not to be a dick :slight_smile:

Cas :slight_smile:

not always scared enough :slight_smile: