IntStream.sum
Remi Forax
forax at univ-mlv.fr
Wed Jan 16 09:53:56 PST 2013
On 01/16/2013 05:37 PM, Kevin Bourrillion wrote:
> On Wed, Jan 16, 2013 at 7:53 AM, Remi Forax <forax at univ-mlv.fr
> <mailto:forax at univ-mlv.fr>> wrote:
>
> My argument is when you reduce over integers, you want an integer
> as result, like int + int is an int.
>
>
> This argument seems overly abstract when we're trying to address the
> very concrete problem of overflow. Overflow is already a problem for
> int + int, but gets a lot more worrisome when summing a stream.
>
>
> Reducing over integers and get a long should not be the default
> behavior because it's not what people espect.
>
>
> It's not that unexpected either.
>
> I like the long return value, because the chance of 63-bit overflow is
> so incredibly less likely than 31-bit overflow.
given that most people will cast the result to int, this argument is moot.
>
> If someone want a long, using reduce is better because reduce
> require to pass an operator so user can choose the exact semantics
> he want, throwing an exception or using a BigInteger is perhaps
> better.
>
>
> A long return value also lets him choose the semantics he wants: he
> can then either do a plain cast, checked cast or saturated cast.
> (Guava provides Ints.checkedCast() and Ints.saturatedCast(), FYI.)
> And that check only has to happen once at the end. The risk of
> 63-bit overflow is the truly esoteric one, and I'm fine with any
> amount of hand-rolling needed for that.
checkedAdd seems as fast as + in a loop nowadays, I think it's because
the calculation is bound by the cost of the memory accesses not by the
CPU processing. Used in a pipeline that does megamorphic calls it will
be invisible.
Anyway, i'm clearly in minority and I don't think this issue deserve a
long thread,
so I'm fine with the long return value.
Rémi
More information about the lambda-libs-spec-observers
mailing list