C#中++ i vs i + = 1有什么性能差异? [英] Is there any performance difference with ++i vs i += 1 in C#?

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

问题描述

i + = a应该等于i = i + a. 在a == 1的情况下,据说它比++ i效率低,因为它涉及更多的内存访问;还是编译器会使其与++ i完全相同?

i += a should be equivalent to i = i + a. In the case where a == 1, this is supposedly less efficient as ++i as it involves more accesses to memory; or will the compiler make it exactly the same as ++i?

推荐答案

很容易回答:C#编译器将C#源代码转换为IL操作码.没有专用的IL操作码可以执行与++运算符等效的操作.如果您使用ildasm.exe工具查看生成的IL,这很容易看到.此示例C#代码段:

It is easy to answer: the C# compiler translates C# source code to IL opcodes. There is no dedicated IL opcode that performs the equivalent of the ++ operator. Which is easy to see if you look at the generated IL with the ildasm.exe tool. This sample C# snippet:

        int ix = 0;
        ix++;
        ix = ix + 1;

生成:

  IL_0000:  ldc.i4.0               // load 0
  IL_0001:  stloc.0                // ix = 0

  IL_0002:  ldloc.0                // load ix
  IL_0003:  ldc.i4.1               // load 1
  IL_0004:  add                    // ix + 1
  IL_0005:  stloc.0                // ix = ix + 1

  IL_0006:  ldloc.0                // load ix
  IL_0007:  ldc.i4.1               // load 1
  IL_0008:  add                    // ix + 1
  IL_0009:  stloc.0                // ix = ix + 1

它会生成完全相同的代码.抖动无能为力,只能生成同样快的机器代码.

It generates the exact same code. Nothing the jitter can do but generate machine code that is equally fast.

pre/post增量运算符是C#中的语法糖,请在使代码更易读的地方使用它.也许更相关:避免在 清晰的地方避免使用它.他们确实有一个诀窍,可让您创建具有太多副作用的表达式.

The pre/post increment operator is syntax sugar in C#, use it wherever it makes your code more legible. Or perhaps more relevant: avoid it where it makes it less legible. They do have a knack for letting you create expressions that have too many side-effects.

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

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