Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A hot path calls Status.values() inside a loop and a profiler shows allocation from it. Why, and what do you do?

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.

Java
enum Status { NEW, PAID, SHIPPED, DELIVERED, CANCELLED }
Status[] a = Status.values();
Status[] b = Status.values();
System.out.println(a == b); // false: two separate arrays
a[0] = null;
System.out.println(Status.values()[0]); // NEW: the internal array is safe

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.

Java
enum Status {
NEW("N"), PAID("P"), SHIPPED("S"), DELIVERED("D"), CANCELLED("C");
final String code;
Status(String code) { this.code = code; }
static Status fromCode(String code) {
for (Status s : values()) { // new array on every call
if (s.code.equals(code)) return s;
}
throw new IllegalArgumentException("Unknown status code: " + code);
}
}
// called for each of 2,000,000 rows in an import
for (Row r : rows) r.status = Status.fromCode(r.statusCode); // 2,000,000 arrays, about 80 MB of garbage

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.

Java
enum Status {
NEW, PAID, SHIPPED, DELIVERED, CANCELLED;
private static final Status[] VALUES = values(); // one copy, made once
public static final List<Status> ALL = List.of(VALUES); // safe to share: unmodifiable
static Status byIndex(int i) { return VALUES[i]; } // no allocation
}
Status.ALL.get(2); // SHIPPED
Status.ALL.set(0, null); // UnsupportedOperationException

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.

Java
enum Status {
NEW("N"), PAID("P"), SHIPPED("S"), DELIVERED("D"), CANCELLED("C");
final String code;
Status(String code) { this.code = code; }
private static final Map<String, Status> BY_CODE =
Arrays.stream(values()).collect(Collectors.toUnmodifiableMap(s -> s.code, s -> s));
static Status fromCode(String code) {
Status s = BY_CODE.get(code); // one hash lookup, no new array
if (s == null) throw new IllegalArgumentException("Unknown status code: " + code);
return s;
}
}
Status.fromCode("S"); // SHIPPED
Options for the lookup
ApproachAllocation per callCost per lookup
Scan over values()one array (about 40 bytes)up to 5 string compares
Scan over cached VALUESnoneup to 5 string compares
Static Map by codenoneone hash lookup
valueOf(name)noneone 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.

What to say in the interviewAbout 80 seconds aloud

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.
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/