5 ms·
Also from the beginning of the article: > The task was to compute a sum of all the numbers, skipping the number whenever it is equal to a magic constant. The v
by Inityx 4y ago
Also from the beginning of the article:
> The task was to compute a sum of all the numbers, skipping the number whenever it is equal to a magic constant. The variants differ by the way how skipping is realized:
> 1. We return primitive longs and check if we need to skip by performing a comparison with the magic value directly in the summing loop.
> 2. We return boxed Longs and we return null whenever we need to skip a number.
> 3. We return boxed Longs wrapped in Optional and we return Optional.empty() whenever we need to skip a number.
Seems pretty reasonable to me.
- alkonaut 4y agoAnd the only one that truly would make sense would of course be Optional<long>, i.e. the optional primitive long... First having to declare the value in the one type of four that makes least sense, then praying that the compiler optimizes the allocation of not one but TWO(!) objects(!) in order to represent "maybe a number" is basically why I ragequit Java almost 20 years ago.
- kaba0 4y ago20 years ago there were no generics, so you couldn’t have implemented it that way. You could have written a class OptionalLong { long value; boolean isSet; } at the time and that would have only a single allocation overhead. Alternatively, have an array of longs and a boolean array marking which ones are set, with a trivial wrapper object over that for essentially zero overhead. Java’s tradeoffs are maintainability in huge teams over multiple years with relatively fast performance even if you write your code very naively, with top notch tooling, observability, etc. In the rare case you have to optimize in the hot loops you can allow to have less readable code like I mentioned.
- alkonaut 4y ago> 20 years ago there were no generics, so you couldn’t have implemented it that way. You could have written a class OptionalLong That was the actual reason, yeah. Basically having to make IntList and so on. > Java’s tradeoffs are maintainability in huge teams over multiple years with relatively fast performance When I did switch to C# in 2003, it was very young. Since then generics have been bolted on and so on, but I didn't find any hit to maintainability due to this. What I do think was sad though is that when Generics were bolted on (and value types obviously were there all along), that the APIs didn't immediately include some easy and obvious wins like Option<T>. Those have been reimplemented since ad nauseam.