是否有与++ i和i在C#++的性能差异? [英] Is there any performance difference between ++i and i++ in C#?

查看:79
本文介绍了是否有与++ i和i在C#++的性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有使用类似之间的性能差异。

Is there any performance difference between using something like

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

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

或者是编译器能够以这样的方式它们的情况下同样快,他们是功能上等同的

or is the compiler able to optimize in such a way that they are equally fast in the case where they are functionally equivalent?

编辑:
这是因为问我有一个关于它的同事的讨论,并不是因为我认为它在任何实际意义上有用的优化。这在很大程度上是学术性的。

This was asked because I had a discussion with a co-worker about it, not because I think its a useful optimization in any practical sense. It is largely academic.

推荐答案

有在生成的中间code ++为i和i在这种情况下++没有区别。鉴于此程序:

There is no difference in the generated intermediate code for ++i and i++ in this case. Given this program:

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 code是两个回路相同的:

The generated IL code is the same for both loops:

  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编译器可以在某些情况下,这将有利于一个版本比其他做了一些优化。如果有这样一个优化,但是,它很可能只影响一个循环的最后(或者第一)迭代

That said, it's possible (although highly unlikely) that the JIT compiler can do some optimizations in certain contexts that will favor one version over the other. If there is such an optimization, though, it would likely only affect the final (or perhaps the first) iteration of a loop.

在短,会有简单的pre-增量或在你所描述的循环结构的控制变量的增量后的运行没有什么区别。

In short, there will be no difference in the runtime of simple pre-increment or post-increment of the control variable in the looping construct that you've described.

这篇关于是否有与++ i和i在C#++的性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆