EDIT 3
If I go back to the original test with a fixed synchronization error, I get a similar result.
Conditional took 67 ms
Normal took 83 ms
Caching took 73 ms
, Ternary/Conditional for. , , , if Ternary/Conditional, , , / , .
, if. , , .
2
infact a
Stopwatch reset , Stopwatch.Restart Stopwatch.Start 1000000000,
22404
21403
, CIL. , "" if , Ternary\Conditional, .
, , , / , if. .
, . CIL, if, , , -, , 3 1 2 , ?.
,
using System.Diagnostics;
class Program
{
static void Main()
{
var stopwatch = new Stopwatch();
var conditional = Conditional(10);
var normal = Normal(10);
var cached = Cached(10);
if (new[] { conditional, normal }.Any(x => x != cached))
{
throw new Exception();
}
stopwatch.Start();
conditional = Conditional(10000000);
stopWatch.Stop();
Console.WriteLine(
"Conditional took {0}ms",
stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
normal = Normal(10000000);
stopWatch.Stop();
Console.WriteLine(
"Normal took {0}ms",
stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
cached = Cached(10000000);
stopWatch.Stop();
Console.WriteLine(
"Cached took {0}ms",
stopwatch.ElapsedMilliseconds);
if (new[] { conditional, normal }.Any(x => x != cached))
{
throw new Exception();
}
Console.ReadKey();
}
static int Conditional(int iterations)
{
var ret = 0;
for (int j = 0; j < iterations; j++)
{
ret = (j * 11 / 3 % 5) + (ret % 11 == 4 ? 2 : 1);
}
return ret;
}
static int Normal(int iterations)
{
var ret = 0;
for (int j = 0; j < iterations; j++)
{
if (ret % 11 == 4)
{
ret = 2 + (j * 11 / 3 % 5);
}
else
{
ret = 1 + (j * 11 / 3 % 5);
}
}
return ret;
}
static int Cached(int iterations)
{
var ret = 0;
for (int j = 0; j < iterations; j++)
{
var tmp = j * 11 / 3 % 5;
if (ret % 11 == 4)
{
ret = 2 + tmp;
}
else
{
ret = 1 + tmp;
}
}
return ret;
}
}
x64 . ,
65
148
217
.
ILDASM , , CIL , Conditional .
"", . , , , .
even , .
static int Conditional(bool condition, int value)
{
return value + (condition ? 2 : 1);
}
static int Normal(bool condition, int value)
{
if (condition)
{
return 2 + value;
}
return 1 + value;
}
static int Looper(int iterations, Func<bool, int, int> operation)
{
var ret = 0;
for (var j = 0; j < iterations; j++)
{
var condition = ret % 11 == 4;
var value = ((j * 11) / 3) % 5;
ret = operation(condition, value);
}
}
- , , IL .
... Conditional ...
{
: ldarg.1
: ldarg.0
: brtrue.s T
: ldc.i4.1
: br.s F
T: ldc.i4.2
F: add
: ret
}
... Normal ...
{
: ldarg.0
: brfalse.s F
: ldc.i4.2
: ldarg.1
: add
: ret
F: ldc.i4.1
: ldarg.1
: add
: ret
}