[No0000B7]If else 与 三元表达式? : 效率对比

时间:2024-01-15 14:53:56

先看 if else 一段代码

using System;

class Program
{
private static void Main()
{
int i = ; if (i == ) i = -;
else i = -; Console.WriteLine(i);
}
}

输出 -1

[No0000B7]If else  与 三元表达式? : 效率对比

用IL DASM ("C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\ildasm.exe"vs2015 up3,项目框架.NET Framework 4.5.2)打开

.method private hidebysig static void Main() cil managed
{
.entrypoint
// 代码大小 26 (0x1a)
.maxstack
.locals init ([] int32 i,
[] bool V_1)
IL_0000: nop
IL_0001: ldc.i4.
IL_0002: stloc.
IL_0003: ldloc.
IL_0004: ldc.i4.
IL_0005: ceq
IL_0007: stloc.
IL_0008: ldloc.
IL_0009: brfalse.s IL_000f
IL_000b: ldc.i4.m1
IL_000c: stloc.
IL_000d: br.s IL_0012
IL_000f: ldc.i4.s -
IL_0011: stloc.
IL_0012: ldloc.
IL_0013: call void [mscorlib]System.Console::WriteLine(int32)
IL_0018: nop
IL_0019: ret
} // end of method Program::Main

在看三元表达式? :一段代码

using System;
class Program
{
private static void Main()
{
int i = ; i = i == ? - : -; Console.WriteLine(i);
}
}

输出 -1

[No0000B7]If else  与 三元表达式? : 效率对比

.method private hidebysig static void Main() cil managed
{
.entrypoint
// 代码大小 20 (0x14)
.maxstack
.locals init ([] int32 i)
IL_0000: nop
IL_0001: ldc.i4.
IL_0002: stloc.
IL_0003: ldloc.
IL_0004: brfalse.s IL_000a
IL_0006: ldc.i4.s -
IL_0008: br.s IL_000b
IL_000a: ldc.i4.m1
IL_000b: stloc.
IL_000c: ldloc.
IL_000d: call void [mscorlib]System.Console::WriteLine(int32)
IL_0012: nop
IL_0013: ret
} // end of method Program::Main

[No0000B7]If else  与 三元表达式? : 效率对比

明显,执行效率不一样。三元表达式? :执行效率更高。

using System;
using System.Diagnostics; class Program
{
private static void Main()
{
int i = ; Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int j = ; j < ; j++)
{
if (i == ) i = -;
else i = -;
}
stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start();
for (int j = ; j < ; j++)
{
i = i == ? - : -;
}
stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
}

[No0000B7]If else  与 三元表达式? : 效率对比