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
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.
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.