[JEP Proposal] Constant-Time Enum Size Access (https://gist.github.com/TuranDev/9a20c773d8c698de918da54b2964bf65)

Remi Forax forax at univ-mlv.fr
Tue Nov 18 23:40:26 UTC 2025


What you are proposing is not backward compatible, 
i'm sure there are existing enum classes that declare a field named SIZE. 

And there is a simple solution, use an unmodifiable list. 
For example: 

enum MyEnum { 
public static final List<MyEnum> VALUES = List.of(MyEnum.values()); 
} 

here, MyEnum.VALUES.size() is a constant. 

regards, 
Rémi 

> From: "Turan Suleyman" <turansuleyman at proton.me>
> To: "compiler-dev" <compiler-dev at openjdk.java.net>
> Sent: Wednesday, November 19, 2025 12:04:21 AM
> Subject: [JEP Proposal] Constant-Time Enum Size Access
> (https://gist.github.com/TuranDev/9a20c773d8c698de918da54b2964bf65)

> 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:

>     1.
> A compiler-generated static constant , e.g. public static final int SIZE =
> <number of constants>;

>     2.
> A built-in API method such as MyEnum.size();

> Draft JEP: [ https://gist.github.com/TuranDev/9a20c773d8c698de918da54b2964bf65 |
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20251119/654a956a/attachment.htm>


More information about the compiler-dev mailing list