3 ms·
But `Optional` could have been a value type from the start and had effectively zero overhead, especially if it were specialized for primitive types. There are 8
by jonhohle 4y ago
But `Optional` could have been a value type from the start and had effectively zero overhead, especially if it were specialized for primitive types. There are 8 primitive types, so supporting them all with a value-type optional would not have been the end of the world, even if it was only a language level optimization (e.g. optional becomes a 96-bit-128-bit type and the compiler is responsible for ensuring primitives are wrapped/unwrapped specially).
GNU Trove is a collection library that focuses on optimizing for primitive types and is significantly faster that Java collections which require boxing.
- winrid 4y agoNever heard of Trove, thanks! Have only used fastutil, which looks to be about the same thing.
- kaba0 4y agoThere is OptionalLong in the standard library, though. Java just can’t do generic specialization as of yet, which is necessary for Optional<long> to be a different implementation (+ value types of course)
- jonhohle 4y agoBut `OptionalLong` is a heap allocated object. I’m suggesting a wider primitive that can be passed on the stack (value plus flags to indicate state) bypassing any need for allocation. In Java this can only be provided by the compiler (without resorting to some programming and value convention).
- kaba0 4y agoWell, Java doesn’t specify that it has to be heap allocated and it will in fact not allocate that object if the producer function can be inlined and the escape analysis deems so (which happens surprisingly often). But here is another option if you really want to avoid that allocation (besides of course using ByteBuffer and similar which is always a possibility): https://news.ycombinator.com/item?id=35133577 https://news.ycombinator.com/item?id=35133577
- jonhohle 4y agoIt doesn’t specify, but in practice (at least when I was last using it around 11), it is. Stack allocation has very different semantics than single allocation buffers, though I’m not sure I follow your logic. What is the reason for not making a OptionalLong a 72-bit (or larger if you care about alignment), primitive value but keeping object semantics at the language level? Someone who thinks they have an object OptionalLong is already looking at minimally 112-bits for the class pointer and value on a non-empty value or add another 96-bits onto the if it’s an `Optional<Long>`. What’s missing with the value-type is shared references to the same instance, but for an immutable optional to an immutable long, that doesn’t make much difference in practice. That’s the only drawback I can see. In practice, how often is it important to have identity properties for boxed primitives? That’s already probably caused more bugs than it’s benefits.