EDIT
如果我使用Stopwatch
正确地将迭代次数增加两个数量级,我得到
三进制耗时 22404ms
正常耗时21403ms
这些结果更接近我的预期,让我觉得世界一切都好(如果不是我的代码)。
事实上,三元/条件运算符稍微慢一些。
继从这个问题 https://stackoverflow.com/q/12457432/659190,我有部分answered https://stackoverflow.com/a/12458395/659190.
我在 x64 发布模式下编译此控制台应用程序并启用优化,然后从命令行运行它,而无需附加调试器。
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
var stopwatch = new Stopwatch();
var ternary = Looper(10, Ternary);
var normal = Looper(10, Normal);
if (ternary != normal) {
throw new Exception();
}
stopwatch.Start();
ternary = Looper(10000000, Ternary);
stopWatch.Stop();
Console.WriteLine(
"Ternary took {0}ms",
stopwatch.ElapsedMilliseconds);
stopwatch.Start();
normal = Looper(10000000, Normal);
stopWatch.Stop();
Console.WriteLine(
"Normal took {0}ms",
stopwatch.ElapsedMilliseconds);
if (ternary != normal) {
throw new Exception();
}
Console.ReadKey();
}
static int Looper(int iterations, Func<bool, int, int> operation)
{
var result = 0;
for (int i = 0; i < iterations; i++)
{
var condition = result % 11 == 4;
var value = ((i * 11) / 3) % 5;
result = operation(condition, value);
}
return result;
}
static int Ternary(bool condition, in value)
{
return value + (condition ? 2 : 1);
}
static int Normal(int iterations)
{
if (condition)
{
return = 2 + value;
}
return = 1 + value;
}
}
我没有遇到任何异常,并且控制台的输出接近于,
三进制耗时 107ms
正常耗时230ms
当我将 CIL 分解为两个逻辑函数时,我得到了这个,
... Ternary ...
{
: ldarg.1 // push second arg
: ldarg.0 // push first arg
: brtrue.s T // if first arg is true jump to T
: ldc.i4.1 // push int32(1)
: br.s F // jump to F
T: ldc.i4.2 // push int32(2)
F: add // add either 1 or 2 to second arg
: ret // return result
}
... Normal ...
{
: ldarg.0 // push first arg
: brfalse.s F // if first arg is false jump to F
: ldc.i4.2 // push int32(2)
: ldarg.1 // push second arg
: add // add second arg to 2
: ret // return result
F: ldc.i4.1 // push int32(1)
: ldarg.1 // push second arg
: add // add second arg to 1
: ret // return result
}
虽然Ternary
CIL 有点短,在我看来,任一函数通过 CIL 的执行路径都需要 3 次加载和 1 或 2 次跳转以及返回。为什么Ternary
功能似乎快了一倍。
我知道,在实践中,它们都非常快,而且确实足够快,但是,我想了解其中的差异。