I can't tell that'd be possible - I see the arguments could be evaluated at compile time, but knowing IntStream.rangeClosed will be evaluated at compile time is a leap, to me.
Did you know before you wrote the code that'd happen?
Is it like C? You cross your fingers and hope the compiler unrolls?
> So there's actually no reason to even invoke the streams API there.
While technically correct, in practice it is not the case.
First of all (and this relates to flerchin's comment), it's not actually done at "compile time" in the traditional sense (i.e. when you invoke `javac`). Rather, it is done at runtime when the method is compiled by the JIT.
As for this comment, the call to `IntStream.rangeClosed` will not simply be reduced to `(b - a) + 1` as you suggest (and one reason for this is that streams are far more complex internally than regular iterators). In reality, it will just be (potentially) inlined and then further optimized alongside the rest of the method's code.
Edit: the mentioned previous comment was from flerchin, not meese
Edit 2: I might have misunderstood what you were getting at there. You are sort of correct in that the `count` operation on this stream is optimized, but it is still technically going through the streams API.
It's not clear to me how the streams api did it, but it's clear to me now that the count of a range of integers is just the end minus the start. This is a fast operation, and I'm not sure if it was performed at compile time, by the JIT, or as a specification of the streams api.
The optimization is done in the JDK implementation (math shortcut) and then further taken advantage of by the JIT (inlining and constant folding).
How is this done?
The implementation of a `Spliterator` that is used internally by `IntStream.rangeClosed` overrides the `estimateSize` method to return `((long) upTo) - from + last`, and the `characteristics` method to return, among others, the `Spliterator.SIZED` characteristic. That characteristic indicates that `estimateSize` can be trusted to be exact, and when present, `estimateSize` will be used as a shortcut in the implementation of `Stream.count`, which can be seen in `ReduceOps.makeRefCounting`.