Why is it when I turn on "check for arithmetic underflow/overflow" under C# Project Properties > Build > Advanced, that the following code runs faster (138 ms) than if I turn the option off (141 ms)?
Test Run #1: 138ms with checked arithmetic, 141ms without
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
var s = new Stopwatch();
s.Start();
int a = 0;
for (int i = 0; i < 100000000; i += 3) {
if (i == 1000)
i *= 2;
if (i % 35 == 0)
++a;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);
Console.WriteLine(a);
}
}
On the other hand, if you comment out the if (i == 1000) i *= 2;
, then the checked code runs slower (120 ms) than the unchecked code (116 ms).
Test Run #2: 120ms with checked arithmetic, 116ms without
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
var s = new Stopwatch();
s.Start();
int a = 0;
for (int i = 0; i < 100000000; i += 3) {
if (i % 35 == 0)
++a;
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);
Console.WriteLine(a);
}
}
Process: Manually ran .exe outside Visual Studio from PowerShell prompt repeatedly until resulting timestamp was consistent (± 1 ms); flipped between settings multiple times to ensure consistent results.
Test Box Setup:
- Windows 8.1 Pro x64
- VS2013 Update 2
- Intel Core i7-4500
- default C# Console project template
- Release configuration