1

I am confused whether or not it is advisable to use x += 1 or x = x+1. I know that they both produce the same results. In practical terms, are there any performance gain when using x+=1 instead of x = x+1? Will it make my program run faster?

Ali
  • 56,466
  • 29
  • 168
  • 265
Minelava
  • 221
  • 1
  • 7
  • 21
  • 1
    You haven't specified a language, which makes this question impossible to answer, beyond "focus on readability first" which is pretty much universal... – Jon Skeet Jul 03 '13 at 17:47
  • 1
    If your program is running too slowly because you are adding one the wrong way, then you have much bigger issues. Adding one should *never* be a bottleneck, regardless of how you accomplish it. – abelenky Jul 03 '13 at 17:51
  • @abelenky - Addition `x=x+1` *can* be a bottleneck if `x` is a string :-) – Egor Skriptunoff Jul 03 '13 at 18:19

2 Answers2

5

x += 1 is just syntactical short cut for x = x + 1. AFAIK, No machine (CPU) level instruction set has an instruction to do x += 1 in a single atomic operation. The actual code executed by the CPU should be identical.

Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
  • 3
    Erm what about `INC` on x86? :P – R. Martinho Fernandes Jul 03 '13 at 17:51
  • The x86 INC instruction s not atomic. If you run `INC DWORD PTR [ EAX ]` the low-level decomposition though would look more like: `uOp.load tmp_reg, [ EAX ] ` `uOp.inc tmp_reg ` `uOp.store [ EAX ], tmp_reg ` and therefore is not executed atomically. Clearly, just from common sense, reading the current value, and adding 1 to it are two separate processes. – Charles Bretana Jul 03 '13 at 18:01
2

Any good compiler should give you the same machine code for both expressions.

Loša
  • 2,621
  • 2
  • 14
  • 19
  • 4
    eventually, yes, they all are. No CPU can execute anything except code that matches its internal instruction set. Perhaps sometimes the intermediary machine language version may be skipped, but eventally it has to be in converted into (what should I call it? assembly?) - something that matches, one for one to the CPUs instruction set. – Charles Bretana Jul 03 '13 at 17:53