Before watching the video -- Java (or a JVM language) better be the top of the list.
After watching the video -- 3rd place (losing only to Rust and Swift) isn't terrible, but there is some nuance here that I think the video failed to mention.
For starters, the video made it seem like the reason why Rust and Swift have better enums than Java are for 2 reasons.
Enum types can be an "alias" for a String or a number, while still retaining type safety at compile time.
I think that both of these points have both costs and benefits. And thus, isn't worth pushing Rust and Swift up a tier above Java.
In Java, our enums are homogenous -- no discriminated unions. As the video mentioned, we have an entirely different feature for when we want to model discriminated unions -- we call them sealed types.
There is a very specific reason why we separated that into 2 features, and didn't just jam them into 1 -- performance.
In both Rust and Swift, the second that your enum contains any sort of mutable state, you turn from the flat value into the discriminated union, and you take a significant performance hit. Many of the optimization strategies possible for flat values become either difficult or impossible with discriminated unions.
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
That fact is the achille's heel. And here is an example of how it can forcefully opt you out of a critical performance optimization.
Go back to 6:20 (and 7:23 for Swift), and look at the Dead/Alive enum they made. Because they added the state, that means that any number of Alive instances may exist at any time. That means that the number of Alive entities at any given point of time is unknown. The compiler can't know this information!
Here is something pretty cool you can do when the compiler does know that information.
In Java, our enums can have all sorts of state, but the number of instances are fixed at compile time. Because of that, we have these extremely performance optimized collection classes called EnumSet and EnumMap. These are your typical set and dictionary types from any language, but they are hyper specialized for enums. And here is what I mean.
For EnumSet, the set denotes presence of absence of a value by literally using a long integer type, and flipping the bits to represent presence or absence. It literally uses the index of the enum value, then flips the corresponding bits. The same logic is used in the EnumMap.
This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
By having the 2 features separate, Java got access to a performance optimization.
By allowing enums to be aliases to string/Number and also allowing enums to be discriminated unions, you force your users to make a performance choice when they want to add state to their enum. Java doesn't. And that's why I don't think the logic for Java being A tier is as clear cut as the video makes it out to be. Imo, Java should either be S tier, or the other 2 should be A tier as well.
EDIT -- So, everything I said here was true, but I still lost the argument. Explanation below.
My argument basically boiled down to this -- because Rust (and Swift, I won't keep repeating this) chose to combine both "Enumerated Values" and "Discriminated Unions" into a single feature called enum, then Rust has to accept some tradeoffs when designing their own EnumSet.
My argument was banking on the assumption that, if Rust wanted to maintain true 1-to-1 performance with Java, then the Rust solution would be a fairly ugly bit of code. Hence my comment about "difficult to impossible".
What I didn't account for was Rust Macros.
Yes, if you want feature and performance parity with Java Enums and Java EnumSet, you have to write a LOT of fairly ugly Rust code.
But since Rust has Macros, then only one (unfortunate) Rust coder has to write that implementation. From there, another (even more unfortunate) Rust coder must write a Macro that generates that implementation.
And from there, all other Rust developers can just use the Macro. That was the point that defeated my argument.
There is something to be said about maintainability and level of effort for maintainability. But, with the realization that Rust Macros allow Rust to achieve feature and performance parity with Java, then I accept Java receiving A-tier for this.
Those macros allow Rust to model pretty much any ugly code they want in a fairly clean wrapper, and then other Rust developers never have to interact with those internals. Doing the same in Java is possible (via annotations), but extremely difficult. If that is the basis for why Java deserves A-tier and Rust gets S-tier, I accept that.
I can at least claim that all of my points are still correct, even if they lacked context.
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
That's technically true, but wildly misleading. Java can make these optimizations when enums have state at the cost of only supporting global state. Sure, this might be very performant:
enum Player {
ALIVE,
DEAD,
public int health;
}
But it's also utterly useless if you ever have more than one player. I'd even argue that global mutable state hidden inside of enums is an anti-feature.
EnumSet in java is just a bit vector, you can easily code it in rust, though it doesn't come with the standard library.
The fact that a rust enum can be a classic enum and a discriminated union is irrelevant as the compiler can apply different optimizations to both.
I think you are confused about what enum "state" actually means. In java state is just an attached constant to the enum that is why you can use it in a EnumSet. In rust state is dynamic, if you want to do the same in java you need to use classes which of course don't work with EnumSet.
3 I think you are confused about what enum "state" actually means. In java state is just an attached constant to the enum that is why you can use it in a EnumSet. In rust state is dynamic, if you want to do the same in java you need to use classes which of course don't work with EnumSet.
This statement is incorrect.
Consider the following Java code.
enum ChronoTriggerCharacter
{
Chrono(100, 90, 80),
Marle(50, 60, 70),
//more characters
;
public int hp; //MUTABLE
public final int attack; //IMMUTABLE
public final int defense; //IMMUTABLE
ChronoTriggerCharacter(int hp, int attack, int defense)
{
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public void receiveDamage(int damage)
{
this.hp -= damage;
}
}
(ignore the public modifier, I am making a point here)
I can mutate each of these characters HP. I am not limited to immutable data. These are instances of a class, and with the minor exception of class level generics, anything a class can do, a Java enum value can do.
That means mutable state, methods that mutate that mutable state (and those methods can exist on the enum itself), etc.
I can do this.
Chrono.receiveDamage(10);
And then Chrono's hp will now be 90.
And there will only ever be one single instance of Chrono, ever.
So with that in mind, let's review your points 1 and 2.
For point 1, how would I attach mutable state to my enum in Rust, while also being able to use a bit vector? That's my point -- you would have to separate it out and do something along the lines having that state held somewhere else. With Java, this is just plain OOP.
And for point 2, my argument has been that the discriminated union will not be able to perform as well as the "pure enum", and that Java allows "pure enums" to have mutable state, allowing you to get the "best of both worlds", performance wise.
But someone else has already prompted me for a bench mark. I added a RemindMe somewhere. Ctrl+F and you can find it. That should be the real test.
This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
This needs some data for backing up because I have a feeling that combined with the JVM overhead it will not be able to match Rust.
This needs some data for backing up because I have a feeling that combined with the JVM overhead it will not be able to match Rust.
The quote you replied to said "fastest in the JDK", but it sounds like you are asking me to defend faster than Rust?
I'll take on both points.
(fair warning, it's bed time for me, so I'll be a few hours before my next response)
Fastest in the JDK
First, let's review the implementation.
An enum is an ordered set of values, all of the same type. And when using an EnumSet, because of the ordered nature of enums, one can denote inclusion or exclusion in the EnumSet by simply using a long or long[] (for when >64 enum values). You use the index of the enum value to decide which bit on the long/[] to flip. 1 means included, 0 means excluded.
So modifying inclusion or exclusion is literally just a bit flip. That's a single assembly operation. And when doing your typical Discrete math Union/Intersection/Difference between 2 sets, that's literally just an AND/OR/NOT between the 2 long or long[]. That's about as fast as the computer can get.
So, do I need to provide more evidence than this that this is the fastest option in the JDK?
The literal only one that beats it is Java's Set12 class, which is a set that can literally only hold 2 values lololol. It's another hyper optimization for when you have a set of only 2 values. But if you ever need to go more than 2 values, you are back to an array of addresses, which means that you are back to being outperformed by EnumSet. I just didn't include Set12 because I don't think a set that can literally only hold 2 values is worth mentioning lol.
Faster than Rust
I'm happy to type up a benchmark for this, but I fear that I would be unfair to Rust just due to my ignorance. If that works for you, lmk, then I'll start work on it right away.
But remember, in Java, when adding or removing enum values into a Set, you are just doing raw bit flips and AND/OR/NOT's. You aren't touching any of the Java overhead at all because all of it has been compiled away to a bunch of long and long[] instances. That's the power of the JIT -- it boils down to just a bunch of long after it gets compiled at runtime.
And Rust, by definition of using Discriminated Unions, can't do the same -- it has an unknown number of instances, so how can it use this indexing strategy when instances are being created and deleted dynamically throughout the program's lifecycle? Java's are created on classload, then done.
But like I said, if that's not enough, I'll give a benchmark a shot and post it here. But lmk if that is needed.
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
You are wrong.
enum X { A, B, C }
println!(
"{} {} {} {} {} {}",
std::mem::size_of::<std::num::NonZeroU8>(),
std::mem::size_of::<Option<std::num::NonZeroU8>>(),
std::mem::size_of::<X>(),
std::mem::size_of::<Option<X>>(),
std::mem::size_of::<&u8>(),
std::mem::size_of::<Option<&u8>>(),
);
// 1 1 1 1 8 8
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
The type theory says that type is sum of all possible values so if you know type you already know all values.
added:
Maybe I misunderstood you because the Java types you are talking about are bit masks. Specifically in Rust they are not part of the standard library but there are many third-party implementations of them. In any case this is a unique advantage for Java (although the implementation can be quite good).
Because of that, we have these extremely performance optimized collection classes called EnumSet
added:
I checked the information about EnumSet... it's just a wrapper around bitwise operations. It's a different type that has nothing to do with enum because enums should only be in one state. And it's been around in all programming languages since ancient times. Although a high-level abstraction on top of that is zero-cost is certainly nice (I often use the bitflags package in Rust for example).
While that is a cool optimization, it does not require all enums to be "named constants" like in Java. In fact, there is a library in Rust that does pretty much the same thing as Java's EnumSet: https://docs.rs/enumset/latest/enumset/
This optimization just requires the ability to convert an enum value to an integer and back. For the Rust enumset library above, it achieves this by basically disallowing enums with data from being used with EnumSets. However, it should be possible to implement a mechanism to map enums to integers even when the enum contains data, provided the total number of possible values (the type's "inhabitants") is limited.
For the Rust enumset library above, it achieves this by basically disallowing enums with data from being used with EnumSets.
Yeah, that is sort of my point -- you have to give up the ability to add state directly to your enum.
However, it should be possible to implement a mechanism to map enums to integers even when the enum contains data, provided the total number of possible values (the type's "inhabitants") is limited.
Could you explain this in more detail? I feel like I get it, but I don't want to assume.
I'll say optimizations aside: strictly speaking the sealed class strategy is more flexible than rust/swift's approach.
With sealed classes your variants are actual distinct types. They can also be part of multiple sealed hierarchies at once and the sealed hierarchies can be trees more than one level deep.
So even in that dimension there is an argument for it being "better" (at the very least more expressive, if higher ceremony) than rust or swift
Sorry I fail to see how this is better than Rust's or Ocaml's enums. All languages using sealed classes missed the spot on enums the first time and had to add yet another feature to make them more usable. So the only sure thing is that the language got more awkward. Performance wise, they are most probably in the same ballpark. I haven't checked though.
From a developer's perspective I wouldn't say this is a win. I also fail to see your point about distinct types. In a language with true ADTs, enums values are just values and these can have any type. And you can also add methods on Rust's enums..
From my experience, proper ADT support in any language is a must have as it improves both the quality of your domain modeling as well as it's ease of composition.
I should mention that support for proper matching allows to check patterns at arbitrary nesting depth, and detect both unhandled cases (with examples) and shadowed cases.
The ML language family has had the best enums for decades.
I'll say optimizations aside: strictly speaking the sealed class strategy is more flexible than rust/swift's approach.
Oh, agreed. That's why I think Java's approach is better -- you choose your flexibility, and the flexibility you give up on turns into performance gains. It's great.
With sealed classes your variants are actual distinct types. They can also be part of multiple sealed hierarchies at once and the sealed hierarchies can be trees more than one level deep.
So even in that dimension there is an argument for it being "better" (at the very least more expressive, if higher ceremony) than rust or swift
Are rust and swift not able to nest their own sealed hierarchies? I thought they were, for some reason.
Are rust and swift not able to nest their own sealed hierarchies? I thought they were, for some reason.
Rust's enums can contain other enums to make nested hierarchies. But since they are not proper subtypes, child types can't be automatically converted to parent types. You have to manually implement and call conversion functions (though they are standardized in Rust so the libraries work together).
sealed classes are probably better in a lot of ways, however they require having inheritance and type narrowing, so language differences make it impossible to have them in Rust a bit too early (as the language pretty much doesn't have type matching/narrowing at all)
Yeah, Java Enums are one of the very few times where Java was so far ahead of the curve compared to everyone else.
Back when Java Enums first came out (2005!), there was nothing else like it. And even now, 20 years later, I'd say that the other languages have merely caught up, or provided decent enum alternatives. But none have surpassed it. (unless you are a JVM language, but JVM languages literally compile down to Java bytecode lol, so I'll call that a point for Java)
Java is a fantastic language nowadays. Java 25 came out 3 weeks ago, and everything since Java 17 has been stellar. It's my favorite language of all time and Java enums are my favorite programming language feature of all time (in case the 5000 character essay didn't make that clear lol).
Java enums are my favorite programming language feature of all time
I still battle coworkers who want to use an interface with constants in it, like it is still the dark ages of pre-java 1.5. Java enums are so powerful, they are an underused language feature (at least by my coworkers).
For EnumSet, the set denotes presence of absence of a value by literally using a long integer type, and flipping the bits to represent presence or absence
Wow, Java has bitmasks? What a revolutionary feature. If only Rust had that. /s
Wow, Java has bitmasks? What a revolutionary feature. If only Rust had that. /s
The real trick is not the bitmasks, but being able to know at compile time exactly how many instances are ever going to be created (and thus, how many bits the bitmask needs).
That is the powerful part because we can skip an entire class of validation checks -- that is the performance benefit that Rust can't get, as they chose to enumerate their types rather than their instances of the types.
It took me a while to understand that the author of the message about how cool Java is doesn't understand the difference between an enums, sum types and bitmask at all.
It's actually scary how many upvotes his comment received.
In fact, abstraction over bitwise operations is useful and convenient, but it simply has to be zero-cost.
And to further drive the point home, let me point out another performance optimization that Java got access to because they opted out of including points 1 and 2 directly into their enums.
EnumSet and EnumMap aren't just the fastest Collection classes in the entire JDK, but they are also the lightest. They use the least amount of memory compared to any other Collection class in the entire JDK. Again, it is literally a single bit per enum value lol.
If I have an enum with 10 values, then my EnumSet only needs 10 bits to denote them lol. Obviously, the overhead of classes and the arrays within them adds some tax to that number, but each of those are one time payments.
And that overhead payment is the exact same for every single enum and EnumSet out there (until your enum has more than 64 values -- then it switches from a long to a long[], but again -- a one time payment).
This is stuff that Rust and Swift can't have access to (with state) because they made the choice to put discriminated unions into their enums.
Further reason why I think the logic behind Java being A tier is wrong. It should at least be S tier alongside Rust and Swift. At least then, we can treat it like what it actually is -- a tradeoff. And one that isn't clearly better, one way or the other.
EnumSet and EnumMap aren't just the fastest Collection classes in the entire JDK, but they are also the lightest. They use the least amount of memory compared to any other Collection class in the entire JDK. Again, it is literally a single bit per enum value lol.
There's a solution that the game development scene came up with that needs no storage in the object itself at all, and has only some overhead when changing the state of the object:
Imagine you have a collection of objects that can harm the player, e.g. enemies and bullets in a shoot 'em up game. Instead of storing a boolean "harmful" or an enum "EntityType" in the object, you create object pools called "ActiveEnemies" and "ActiveBullets", and their inactive counterparts. The objects are basically categorized by their address. This eliminates lots of code for loading and branching on object fields, makes the game state smaller, and removes the potential of cache and branch misses. When the object state changes, the objects need to be moved from one pool to another, but that happens relatively rarely (over several seconds instead of frames).
View all comments
36
u/davidalayachew Oct 07 '25 edited Nov 03 '25
Before watching the video -- Java (or a JVM language) better be the top of the list.
After watching the video -- 3rd place (losing only to Rust and Swift) isn't terrible, but there is some nuance here that I think the video failed to mention.
For starters, the video made it seem like the reason why Rust and Swift have better enums than Java are for 2 reasons.
I think that both of these points have both costs and benefits. And thus, isn't worth pushing Rust and Swift up a tier above Java.
In Java, our enums are homogenous -- no discriminated unions. As the video mentioned, we have an entirely different feature for when we want to model discriminated unions -- we call them sealed types.
There is a very specific reason why we separated that into 2 features, and didn't just jam them into 1 -- performance.
In both Rust and Swift, the second that your enum contains any sort of mutable state, you turn from the flat value into the discriminated union, and you take a significant performance hit. Many of the optimization strategies possible for flat values become either difficult or impossible with discriminated unions.
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
That fact is the achille's heel. And here is an example of how it can forcefully opt you out of a critical performance optimization.
Go back to 6:20 (and 7:23 for Swift), and look at the Dead/Alive enum they made. Because they added the state, that means that any number of Alive instances may exist at any time. That means that the number of
Aliveentities at any given point of time is unknown. The compiler can't know this information!Here is something pretty cool you can do when the compiler does know that information.
In Java, our enums can have all sorts of state, but the number of instances are fixed at compile time. Because of that, we have these extremely performance optimized collection classes called EnumSet and EnumMap. These are your typical set and dictionary types from any language, but they are hyper specialized for enums. And here is what I mean.
For EnumSet, the set denotes presence of absence of a value by literally using a
longinteger type, and flipping the bits to represent presence or absence. It literally uses the index of the enum value, then flips the corresponding bits. The same logic is used in the EnumMap.This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
By having the 2 features separate, Java got access to a performance optimization.
By allowing enums to be aliases to string/Number and also allowing enums to be discriminated unions, you force your users to make a performance choice when they want to add state to their enum. Java doesn't. And that's why I don't think the logic for Java being A tier is as clear cut as the video makes it out to be. Imo, Java should either be S tier, or the other 2 should be A tier as well.
EDIT -- So, everything I said here was true, but I still lost the argument. Explanation below.
My argument basically boiled down to this -- because Rust (and Swift, I won't keep repeating this) chose to combine both "Enumerated Values" and "Discriminated Unions" into a single feature called
enum, then Rust has to accept some tradeoffs when designing their own EnumSet.My argument was banking on the assumption that, if Rust wanted to maintain true 1-to-1 performance with Java, then the Rust solution would be a fairly ugly bit of code. Hence my comment about "difficult to impossible".
What I didn't account for was Rust Macros.
Yes, if you want feature and performance parity with Java Enums and Java EnumSet, you have to write a LOT of fairly ugly Rust code.
But since Rust has Macros, then only one (unfortunate) Rust coder has to write that implementation. From there, another (even more unfortunate) Rust coder must write a Macro that generates that implementation.
And from there, all other Rust developers can just use the Macro. That was the point that defeated my argument.
There is something to be said about maintainability and level of effort for maintainability. But, with the realization that Rust Macros allow Rust to achieve feature and performance parity with Java, then I accept Java receiving A-tier for this.
Those macros allow Rust to model pretty much any ugly code they want in a fairly clean wrapper, and then other Rust developers never have to interact with those internals. Doing the same in Java is possible (via annotations), but extremely difficult. If that is the basis for why Java deserves A-tier and Rust gets S-tier, I accept that.
I can at least claim that all of my points are still correct, even if they lacked context.