Code review request: 6282196 There should be Math.mod(number, modulo) methods
Roger.Riggs at oracle.com
Wed Feb 22 16:21:28 UTC 2012
On 02/22/2012 09:37 AM, Stephen Colebourne wrote:
> Can you explain why the mod implementation differs from that in JSR-310?
> The code ((a % b) + b) % b; is short and involves no branches, which
> should aid performance and inlining. Is this to do with accepting a
> negative second argument? Performance testing?
For floorMod, the numeric results are the same but the performance is
The performance difference is very noticeable for long's, using
a single divide and a multiply with the branch is about 1.5 times as fast
as the alternative using two % operations.
For int's the difference was minimal but still faster. I did not
floating point divide.
Since it depends on the performance of the divide instruction it will
be sensitive to specific processors. For interpreters and devices
without floating point hardware (yes they exist) and slower hardware
the number of divides makes sense. I would rather not try to tune for
specific hardware and leave that to the VM.
> I'd like to see performance numbers comparing the two approaches, as
> JSR-310 might need to continue using the double % version if it is
> Similarly, the proposed floorDiv requires evaluation of the complex if
> statement every time, whereas the JSR-310 one only requires an if
> check against zero. Whats the rationale for the difference, which is
> intuitively (non-proven) slower.,
For floorDiv, the results are different when the sign of the divisor is
Using the definition of the largest integer less than the quotient with the
arguments (4, -3) should be -1.3333, the largest integer less than that
The JSR 310 expression (a/v) evaluates to -1.
I choose to be consistent with the Math.floor behavior.
> On 22 February 2012 14:24, Roger Riggs<Roger.Riggs at oracle.com> wrote:
>> 6282196 There should be Math.mod(number, modulo) methods
>> Requests that floor and modulus methods be provided for primitive types.
>> Floor division is pretty straight-forward, rounding toward minus infinity.
>> For modulus of int and long, the sign and range follow the exiting floor
>> in java.util.Math and satisfy the relation that mod(x, y) = (x - floorDiv(x,
>> y) * y).
>> Please review and comment,
>> Thanks, Roger
More information about the core-libs-dev