<div dir="ltr"><div>Hey folks, I was looking into a performance bug report for JRuby that did a lot of numeric work (a prime number detector) and ran into a bottleneck due to our use of Math.multiplyExact.</div><div><br></div><div>Basically, the *Exact methods work great as long as you never actually overflow. If you overflow (too much), the cost of the exception raised massively outweighs any gains from avoiding the manual overflow check.</div><div><br></div><div>I'm wondering two things at this point:</div><div><br></div><div>Question one: Do we need to add versions of these methods that don't raise?</div><div><br></div><div>Obviously we only have one return value, so the failure case needs to be communicated a different way. I'm thinking something like Math.multiplyExact(long a, long b, long failure) that will return the failure value for either an overflow or if the multiply produced that exact value. It would mean one value can never be produced through multiplyExact, but I think that's a tiny cost compared to raising an exception for all overflows.</div><div><br></div><div>Of course you can do two of these in a row with different failure values to avoid falling back on BigInteger logic, and only 1 result out of 2**63 will have to multiply twice.</div><div><br></div><div>Question two: Am I losing the benefits of *Exact if I use the following code to "pre-check" for overflow?</div><div><br></div><div>long high = Math.multiplyHigh(a, b);</div><div>if (high == 0) return Math.multiplyExact(a, b);</div><div>return bigIntegerMultiply(a, b);</div><div><br></div><div>Until there's a no-throw version of Math.*Exact I may have to go with this code.</div><div><br></div><div><div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><b>Charles Oliver Nutter</b><div><i>Architect and Technologist</i></div><div>Headius Enterprises</div><a href="https://www.headius.com" target="_blank">https://www.headius.com</a><div><div><a href="mailto:headius@headius.com" target="_blank">headius@headius.com</a></div></div></div></div></div></div>