Quick revision
The short answer
values() returns a clone of the enum's internal constants array on every call, so the JDK can protect that array from callers who might modify it, and a loop that calls it millions of times allocates millions of short-lived arrays. We fix it by calling values() once and keeping the result in a private static final field, or an unmodifiable List, and by replacing linear scans over values() with a static Map built once. Recent JIT compilers can sometimes remove the copy, but caching is simple and does not depend on that.
What to remember
In this answer, we saw that values() clones the enum's internal array on every call, to protect it from modification, so calling it in a hot loop creates a stream of short-lived arrays. We fixed it by caching the array once in a private static final field, sharing an unmodifiable List with outside code, and replacing linear scans with a static Map built once with toUnmodifiableMap. The JIT may remove the copy through escape analysis, but caching is simple and does not depend on it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
values() returns a clone of the enum's internal constants array on every call, so the JDK can protect that array from callers who might modify it, and a loop that calls it millions of times allocates millions of short-lived arrays. We fix it by calling values() once and keeping the result in a private static final field, or an unmodifiable List, and by replacing linear scans over values() with a static Map built once. Recent JIT compilers can sometimes remove the copy, but caching is simple and does not depend on that.
Background to this question
A profiler showing allocation from Status.values() surprises many developers, because the method looks like a simple getter. This question checks whether we know what values() really does, can read an allocation profile, and can fix a hot path without over-engineering. In this answer, we will see why values() allocates, reproduce the problem, cache the array correctly, replace scans with a lookup map, and talk about when the JIT might make all of this unnecessary.
1Why values() Allocates
For every enum, the compiler generates a private static array holding all constants, often named $VALUES, and a public values() method. Java arrays are always mutable: anyone holding a reference can overwrite an element. If values() returned the internal array, one careless caller could set an element to null and break every other caller, and also valueOf(), which depends on the same data. So values() returns $VALUES.clone(), a brand-new array each time.
The copy is small, an array header plus five references, about 40 bytes. Once is nothing. But a hot path, code that runs for every request, every message or every row, can call it millions of times a second, and then it is gigabytes of garbage per minute.
2Reproducing the Hot Path
A typical case is a lookup by an external code, written as a scan over values() inside a method that is called for every incoming record.
An allocation profiler, such as JFR's allocation sampling or async-profiler in alloc mode, shows Status.values() as a top allocation site under fromCode(). The garbage is short-lived, so young-generation collections clean it cheaply, but more frequent collections still cost CPU and add latency, and the linear scan compares strings for every row.
3Fix 1: Cache the Array Once
The direct fix is to call values() once, when the enum class initializes, and keep the result in a field. The field must be private, because the array is still mutable: exposing it would bring back exactly the risk the clone protects against.
Notice that the cached field is declared after the constants. That is required: enum constants are always created first in the static initializer, and fields declared later are initialized after them, so values() already sees all constants when VALUES is assigned. When code outside the enum needs all constants, we share the unmodifiable List rather than the array.
4Fix 2: A Static Map for Lookups
Caching the array removes the allocation but keeps the linear scan. For lookups by a code, a Map built once is better: it removes both the allocation and the comparisons, and it states the intent clearly.
| Approach | Allocation per call | Cost per lookup |
|---|---|---|
Scan over values() | one array (about 40 bytes) | up to 5 string compares |
| Scan over cached VALUES | none | up to 5 string compares |
| Static Map by code | none | one hash lookup |
valueOf(name) | none | one internal map lookup |
toUnmodifiableMap also fails at startup if two constants share a code, which turns a copy-paste mistake into an immediate, obvious error instead of a lookup that silently returns the first match. For lookups by name, valueOf() already uses an internal map and does not clone the array, so it is fine to call on a hot path.
5Will the JIT Remove the Copy Anyway?
Sometimes. HotSpot's C2 compiler performs escape analysis: if it can prove that an allocated object never leaves the method, it may avoid creating it on the heap at all. A cloned array that is only iterated locally can be a candidate, so in some benchmarks the allocation disappears once the method is compiled.
But we should not rely on it. Escape analysis works only after the method is hot and compiled, gives up when inlining fails or the method is too large, and behaves differently across JDK versions and with the Graal compiler. In our case the profiler already showed the allocation in production, which means the optimization did not apply there. A private static final field costs one line and works on every JVM, so caching is the reliable choice.
6Follow-up questions
Is it safe to make the cached array public if we document that nobody should change it?
No. Documentation does not stop a bug in some other module from writing to it, and a single null element would break every caller. Keep the array private, and expose an unmodifiable List, such as List.of(values()), for outside code.
Do EnumSet.allOf() or Class.getEnumConstants() avoid the copy?
No. EnumSet.allOf() creates a new set each time, and getEnumConstants() also returns a copy of the constants array. If we need all constants repeatedly, we cache once, whichever method we use to get them.
Should every enum get a cached VALUES field?
Only where the profiler or a clearly hot path shows a need. For code that runs once per request or at startup, plain values() is clearer and its cost is negligible.
7Conclusion
In this answer, we saw that values() clones the enum's internal array on every call, to protect it from modification, so calling it in a hot loop creates a stream of short-lived arrays. We fixed it by caching the array once in a private static final field, sharing an unmodifiable List with outside code, and replacing linear scans with a static Map built once with toUnmodifiableMap. The JIT may remove the copy through escape analysis, but caching is simple and does not depend on it.
Open with
values() looks like a getter, but it returns a clone of the enum's internal constants array every time. The JDK has to do that because arrays are mutable, and if it returned the internal array, any caller could overwrite an element and break every other caller and valueOf.
Then, if they want more
So a loop that calls values() for every record allocates a new small array each time, and with a couple of million records that becomes tens of megabytes of garbage and more frequent young collections, which is what the profiler is showing. The usual pattern behind it is a fromCode method that scans values() for a matching code.
I would fix it in two ways. First, cache the array once in a private static final field, declared after the constants, and if outside code needs all constants, expose List.of of it, which is unmodifiable.
Second, for lookups by code, build a static Map once with Collectors.toUnmodifiableMap, which removes both the allocation and the linear scan, and also fails fast at startup if two constants share a code.
C2's escape analysis can sometimes eliminate the clone, but it depends on inlining and compilation, and the profiler shows it did not happen here, so caching is the reliable fix.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A hot path calls Status.values() inside a loop and a profiler shows allocation from it....": https://scrivio-interview-library.netlify.app/java/enums/f605555e3f/