Is there any performance difference with ++i vs i += 1 in C#?

后端 未结 5 702
半阙折子戏
半阙折子戏 2021-01-19 12:42

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 mak

5条回答
  •  日久生厌
    2021-01-19 13:14

    It depends. In theory, given a sufficiently naive compiler, ++x might well be more efficient than x += 1.

    However, I don't know of such a naive compiler.

    • if the value of the operand is known at compile-time, then the compiler can optimize the operation.
    • if the value can be determined to be constant at run-time, then JIT compiler can optimize the operation as well.

    Moreover, modern CPUs are highly complex beasts, which can execute a lot of operations in parallel, and quite often, "simple" operations like these can be entirely hidden by running them in parallel with larger, more complex ones.

    A good rule of thumb, when optimizing and just when writing in general is to express your intent as clearly as possible.

    That makes it easier for other programmers to read your code, but it also makes it easier for the compiler to do so.

    If you want to increment a value, use the increment operator (++), because it describes exactly what you want to do.

    If you want to add a variable or unknown value, use the += operator, because that is what it's for.

    If you're clear about your intentions, then the compiler gets more information about your code, and can optimize accordingly.

    If you write x += 1, you're really trying to trip up the compiler. You're saying "use the general-purpose addition operator to add one to x". Then the compiler has to figure out "ok, you said to use general-purpose addition, but I can see that's nto necessary, so I'm just going to increment instead". You could have told it that. Now, instead, you have to rely on the compiler being clever.

提交回复
热议问题