[JEP Proposal] Constant-Time Enum Size Access (https://gist.github.com/TuranDev/9a20c773d8c698de918da54b2964bf65)
Ron Pressler
ron.pressler at oracle.com
Tue Nov 18 23:21:55 UTC 2025
Before proposing anything, I would start with focusing on the problem.
You mention allocation and performance, but not every `new X[3]` necessarily allocates anything, and even when it does, there isn’t necessarily a performance issue. Even if there is a problem, a size method or field is not necessarily the right solution.
So it’s best to first identify a problem and then let the JDK maintainers come up with an appropriate solution. Do you have an example of a real program where obtaining the number of enum values makes up a significant portion of the profile and/or causes some memory-related issues?
— Ron
P.S.
Your document mentions “zero-GC”, and I just want to point out that with the JDK’s more modern GCs, zero runtime allocations does not mean zero GC. In fact, allocating a new object can result in less GC work than mutating and sometimes even reading an old object. An allocation rate that’s too high can cause a lot of GC work, but so can an allocation rate that’s too low (not with the old GCs, but with the new ones). Avoiding allocations is no longer a good approach to minimising latencies in recent versions of the JDK.
> On 18 Nov 2025, at 23:04, Turan Suleyman <turansuleyman at proton.me> wrote:
>
> Hi all,
> I’d like to start a discussion/gather feedback about a "small" quality of life enhancement to java.lang.Enum to add a constant-time, allocation-free way to obtain the number of constants in an enum type.
> Today, the usual approach is: int n = MyEnum.values().length;
> This creates a new array on every call, which is both non-constant time and allocates memory unnecessarily.
> Since the number of enum constants is fixed and known at compile time, this information could be exposed more efficiently.
> I’ve written a draft JEP describing two possible designs:
> • A compiler-generated static constant, e.g.
> public static final int SIZE = <number of constants>;
> • A built-in API method such as
> MyEnum.size();
> Draft JEP: https://gist.github.com/TuranDev/9a20c773d8c698de918da54b2964bf65
> I’d appreciate feedback on:
> • Whether this seems like a worthwhile enhancement
> • Preference between the two design options
> • Whether anyone would be interested in sponsoring the JEP ( or rolling the change into an open piece of work) if there’s agreement to pursue it.
> Thank you for your time and thoughts.
> Best regards,
> Turan
More information about the compiler-dev
mailing list