c# - 在 C# 中,++i 和 i++ 之间有什么性能差异吗?

标签 c# operators performance

使用类似的东西之间是否有任何性能差异

for(int i = 0; i < 10; i++) { ... }

for(int i = 0; i < 10; ++i) { ... }

或者编译器是否能够以这样的方式进行优化,使它们在功能相同的情况下同样快?

编辑: 之所以这样问是因为我与一位同事就此进行了讨论,而不是因为我认为它在任何实际意义上都是有用的优化。它主要是学术性的。

最佳答案

在这种情况下,++i 和 i++ 生成的中间代码没有区别。给定这个程序:

class Program
{
    const int counter = 1024 * 1024;
    static void Main(string[] args)
    {
        for (int i = 0; i < counter; ++i)
        {
            Console.WriteLine(i);
        }

        for (int i = 0; i < counter; i++)
        {
            Console.WriteLine(i);
        }
    }
}

两个循环生成的 IL 代码是相同的:

  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  // Start of first loop
  IL_0002:  ldc.i4.0
  IL_0003:  stloc.0
  IL_0004:  br.s       IL_0010
  IL_0006:  ldloc.0
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000c:  ldloc.0
  IL_000d:  ldc.i4.1
  IL_000e:  add
  IL_000f:  stloc.0
  IL_0010:  ldloc.0
  IL_0011:  ldc.i4     0x100000
  IL_0016:  blt.s      IL_0006
  // Start of second loop
  IL_0018:  ldc.i4.0
  IL_0019:  stloc.0
  IL_001a:  br.s       IL_0026
  IL_001c:  ldloc.0
  IL_001d:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0022:  ldloc.0
  IL_0023:  ldc.i4.1
  IL_0024:  add
  IL_0025:  stloc.0
  IL_0026:  ldloc.0
  IL_0027:  ldc.i4     0x100000
  IL_002c:  blt.s      IL_001c
  IL_002e:  ret

也就是说,JIT 编译器有可能(尽管可能性很小)可以在某些上下文中进行一些优化,使一个版本优于另一个版本。但是,如果存在这样的优化,它可能只会影响循环的最终(或可能是第一次)迭代。

简而言之,在您所描述的循环结构中,控制变量的简单预增量或后增量的运行时间没有区别。

关于c# - 在 C# 中,++i 和 i++ 之间有什么性能差异吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/467322/

相关文章:

c# - 从另一个线程更新标签

java - 代码逻辑 Guava 的 mightContain

c - ==符号是什么意思?

c++ - 成员(member)权限差异

c++ - 获取运行特定进程的处理器数量

c - 使用 XPath 和 libxml2 检查祖先的最快方法

Java:从 block 中的数组列表创建数组的有效方法

c# - 此 SqlParameterCollection 不包含 ParameterName 为 '@UserId' 的 SqlParameter

c# - Rest call WebException 401 Unauthorized only in mixed authentication webapp

c# - 任务并行库 WaitAny 设计