What is the difference between System.Math.DivRem() and the % operator?
3 Answers
% gives you the remainder of a division and discards the quotient altogether, while DivRem() calculates and returns both the quotient and the remainder.
If you're only concerned about the remainder of a division between two integers, use %:
int remainder = 10 % 3; Console.WriteLine(remainder); // 1 If you need to know how many times 10 was divided by 3 before having a remainder of 1, use DivRem(), which returns the quotient and stores the remainder in an out parameter:
int quotient, remainder; quotient = Math.DivRem(10, 3, out remainder); Console.WriteLine(quotient); // 3 Console.WriteLine(remainder); // 1 4 Comments
/ operator instead of %: int quotient = 10 / 3;Dim quotient As Integer = 10 \ 3double result = a / (double)b; That is the non-integer result of a division of two integers.It is an optimization. Some processors are able to compute both values at the same time. Other processors can't divide in hardware (and must use, very slow, software routines).
In either case (unless you have a smart compiler) you can end up computing the same division twice. Since divisions are never fast, on any processor (even when implemented in hardware), then using Math.DivRem gives the JIT a nice 'hint' to compute the values only once.
iirc Mono does not implement this optimization, and I'm not even sure if MS does.
1 Comment
It could have been an optimization, but unfortunately produces the same IL as a division PLUS a mod operation.
On typical architectures (x86 & friends) the two can be obtained from a single operation, but .NET JIT seems not to optimize that (in my tests).
So the following two are equivalent:
quotient = Math.DivRem(10, 3, out remainder); VS:
quotient = 10 / 3; remainder = 10 % 3; Except the later is more readable.
For the record this ugly option is faster on x86 & x64:
quotient = 10 / 3; remainder = 10 - (3*quotient); Hopefully the JIT will improve some day to optimize the two operations into a single one, since it is trivial.