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?

3
  • 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 3, 2013 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 3, 2013 at 17:51
  • @abelenky - Addition x=x+1 can be a bottleneck if x is a string :-) Jul 3, 2013 at 18:19

2 Answers 2

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.

2
  • 3
    Erm what about INC on x86? :P Jul 3, 2013 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. Jul 3, 2013 at 18:01
2

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

1
  • 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. Jul 3, 2013 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.