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

先看 if else 一段代码

复制代码
using System;

class Program
{
    private static void Main()
    {
        int i = 0;

        if (i == 0) i = -1;
        else i = -2;

        Console.WriteLine(i);
    }
}
复制代码

输出 -1

用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 2
    .locals init ([0] int32 i,
    [1] bool V_1)
    IL_0000: nop
    IL_0001: ldc.i4.0
    IL_0002: stloc.0
    IL_0003: ldloc.0
    IL_0004: ldc.i4.0
    IL_0005: ceq
    IL_0007: stloc.1
    IL_0008: ldloc.1
    IL_0009: brfalse.s IL_000f
    IL_000b: ldc.i4.m1
    IL_000c: stloc.0
    IL_000d: br.s IL_0012
    IL_000f: ldc.i4.s -2
    IL_0011: stloc.0
    IL_0012: ldloc.0
    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 = 0;

        i = i == 0 ? -1 : -2;

        Console.WriteLine(i);
    }
}
复制代码

输出 -1

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

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

复制代码
using System;
using System.Diagnostics;

class Program
{
    private static void Main()
    {
        int i = 0;

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        for (int j = 0; j < 100000000; j++)
        {
            if (i == 0) i = -1;
            else i = -2;
        }
        stopwatch.Stop();

        Console.WriteLine(stopwatch.ElapsedMilliseconds);

        stopwatch.Reset();

        stopwatch.Start();
        for (int j = 0; j < 100000000; j++)
        {
            i = i == 0 ? -1 : -2;
        }
        stopwatch.Stop();

        Console.WriteLine(stopwatch.ElapsedMilliseconds);
    }
}
复制代码

 

 

posted @   CharyGao  阅读(1890)  评论(4编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示