Improve Math.DivRem performance
authorStephen Toub <stoub@microsoft.com>
Tue, 15 Nov 2016 12:28:20 +0000 (07:28 -0500)
committerStephen Toub <stoub@microsoft.com>
Tue, 15 Nov 2016 12:28:20 +0000 (07:28 -0500)
Until the JIT is able to eliminate one of the two idiv operations, using a multiplication and subtraction is measurably faster than an extra division.

src/mscorlib/src/System/Math.cs

index cf2b0ee..9ff0a9f 100644 (file)
@@ -726,13 +726,21 @@ namespace System {
         }
 
         public static int DivRem(int a, int b, out int result) {
-            result =  a%b;
-            return a/b;
+            // TODO https://github.com/dotnet/coreclr/issues/3439:
+            // Restore to using % and / when the JIT is able to eliminate one of the idivs.
+            // In the meantime, a * and - is measurably faster than an extra /.
+            int div = a / b;
+            result = a - (div * b);
+            return div;
         }
 
         public static long DivRem(long a, long b, out long result) {
-            result =  a%b;
-            return a/b;
+            // TODO https://github.com/dotnet/coreclr/issues/3439:
+            // Restore to using % and / when the JIT is able to eliminate one of the idivs.
+            // In the meantime, a * and - is measurably faster than an extra /.
+            long div = a / b;
+            result = a - (div * b);
+            return div;
         }
     }
 }