2

S++ or S=S+1, which can be recommended to increment the value by 1 and why?

I thinkS++ should be preferred, as it is single machine instruction (INC) internally. Make me correct if I'm wrong. Other way I think both are same except ++ is unary and its post-increment and operator overloading is different for both.

Does is make any difference in C#?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 6
    Don't forget `S+=1` – Sean Jan 17 '17 at 09:30
  • yes, @Sean ofcourse. – Vivek Nuna Jan 17 '17 at 09:31
  • I think in c# `S++` uses temp variable so its not single instruction, its probably more than just `INC` – M.kazem Akhgary Jan 17 '17 at 09:32
  • @M.kazemAkhgary Why do you think so? – Patrick Hofman Jan 17 '17 at 09:33
  • 5
    None of the above. If you want to increment a value by `1` and don't care about the previous value, use `++S`. – IInspectable Jan 17 '17 at 09:33
  • *I thinkS++ should be preferred, as it is single machine instruction (INC) internally* possibly, but an optimizer will likely figure out `S=S+1` does just INC and will use it. – stijn Jan 17 '17 at 09:34
  • @IInspectable but why ++S? why not others ? – Vivek Nuna Jan 17 '17 at 09:35
  • 1
    To be honest, I only use the `++` operator in `for` loops, and for nearly any other case the `+=` operator (in both languages, even if I mostly do C#). In almost every application, this won't be the bottleneck, so I don't care about this "optimization". But I do care about readibility. – Lukas Körfer Jan 17 '17 at 09:35
  • @PatrickHofman because of the difference between post and pre increment. http://stackoverflow.com/a/3346729/4767498 – M.kazem Akhgary Jan 17 '17 at 09:36
  • 1
    Why? Because those are the precise semantics you want to convey. – IInspectable Jan 17 '17 at 09:36
  • Have you used the debugger to view what code is actually generated - this may give an idea of which is best. – PaulF Jan 17 '17 at 09:38
  • 1
    @PaulF: A debugger is most valuable when using it on a debug build. Debug builds usually have optimizations disabled, so you won't see the code that you will eventually ship. Besides, you should optimize for readability first and foremost, and deal with performance, where and when it matters. – IInspectable Jan 17 '17 at 09:42
  • I immediately parse `++S;` as "increment S". With `S = S + 1;` it takes a few microseconds longer for me to parse. So `++S` is better IMHO. ;) – Matthew Watson Jan 17 '17 at 09:46
  • can anybody please explain in terms of machine instructions? – Vivek Nuna Jan 17 '17 at 09:47
  • As said, it's hard to predict which machine instructions will be generated. Look at the assembly first. – stijn Jan 17 '17 at 09:48
  • The machine instructions are generated at the time of running so cannot easily be seen - see this : http://stackoverflow.com/questions/24949940/does-jit-convert-the-binary-code-of-il-into-binary-machine-code - I think if the difference in timing between the various methods of incrementing is so critical to your application then maybe C# is the wrong tool for the job. – PaulF Jan 17 '17 at 09:54
  • because C# memory management is different from C++ – Vivek Nuna Jan 17 '17 at 10:06
  • 1
    If `S` is an integer, the IL generated is identical for `++S`, `S++`, `S += 1` and `S = S + 1`. This is easy to see using a decompiler to inspect the IL. It also makes no difference whether it's a debug or release build. – Matthew Watson Jan 17 '17 at 10:13
  • @MatthewWatson yes, IL code is same for all. Is there any other parameter which can affect the performance in C# – Vivek Nuna Jan 17 '17 at 10:15
  • @viveknuna If the IL code is the same, then it's the same; there isn't anything other than the IL which is executed (after being turned into assembler at runtime). – Matthew Watson Jan 17 '17 at 10:17

5 Answers5

16

You should never try to do such tiny optimizations. The modern compilers are smart enough to generate identical assembler code for all 3 options (++i, i+=1, i=i+1) for almost all cases.

Yes, sometimes you can gain some tiny performance boost, for example, using prefix ++ instead of postfix for some class with very complicated ++ operators, but in vast majority of cases part of your program which takes most time is not increments, so to achieve some real results you should profile your code on real (or close to real) test and find less effective frequently used pieces of code.

Also, there's a more important thing to consider - it's code readability. In vast majority of situations it's more important than performance, and only in the most time-critical pieces of code we can sacrifice readability for performance (and even there, not always! sometimes it's better just to add more hardware).

So, my recommendation would be use the option which states your idea in the most clear way.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
  • But if I'm doing this for some complex datatype, It will affect the performance. – Vivek Nuna Jan 17 '17 at 09:43
  • @viveknuna yes if that's involved in hot-path i.e the part of code which gets executed the most during your application life time – M.kazem Akhgary Jan 17 '17 at 09:44
  • 2
    @viveknuna: If you are doing this for a data type, the defines its own increment operator, you cannot contrast `++S` with `S=S+1` anyway. They might do different things, and the latter may not even be legal. – IInspectable Jan 17 '17 at 09:46
  • can anybody please explain in terms of machine instructions? – Vivek Nuna Jan 17 '17 at 09:48
  • The one place it's worth getting in the habit of doing ``++j`` rather than ``j+1`` is iterators for loops. Most iterators support increment, but not all of them support _addition by n_. – Chuck Walbourn Jan 17 '17 at 16:50
  • 1
    @ChuckWalbourn You right, and also many static code analyzers warn about unoptimal code if the iterator is incremented by any other method than prefix `++`. – alexeykuzmin0 Jan 17 '17 at 16:52
4

Back in the good old days, this sort of thing made a difference. I used to look at the generated machine code, then tweak the C source to get an extra 10% speed improvement.

Not any more. You cannot predict the speed from looking at machine code.

  • Many of the optimizations these days are done in the CPU.
  • The IL code is optimized again at runtime, for the processor it is running on, so as a developer you never get to see the instructions which are executed.
  • CPUs are so fast that it hardly matters.

You could try testing the different ways of incrementing, see which one is faster. Once you've got bored with that, stop worrying about speed and concentrate on writing clear, bug-free code.

  • 1
    *Many of the optimizations these days are done in the CPU.* No, code-gen is still done by software, and it's up to a smart compiler to emit the same asm for `i++` as for `++i` or `i = i + 1`. But fortunately compilers *are* smart. Also, if you know what you're doing you can still look at asm and make predictions about speed. Static analysis for out-of-order execution CPUs is different from old in-order machines, but [still possible for simple loops or blocks.](/questions/51607391) – Peter Cordes Oct 27 '18 at 17:28
3

C++ has both pre and post-increment operators.
Pre-increment operator is usually faster as already answered here.
(mostly because compilers can optimize it better, and it does not require a temporary copy of the old value to be returned).

Community
  • 1
  • 1
roalz
  • 2,699
  • 3
  • 25
  • 42
  • That only applies for class types with overloaded increment operators that don't get fully inlined and optimize away any copying. For primitive integer types, there's usually no difference. So you could say "pre-increment is at least as fast", or "not slower". Or post-increment *can* be slower. – Peter Cordes Oct 27 '18 at 17:24
  • Pre-increment can be slower. – BeeOnRope Oct 27 '18 at 20:34
1

Between incrementing a variable s by doing s = s + 1 OR s++, we first need to accept that the operation in itself is really basic, simple and straightforward. We are basically incrementing a value stored in a variable by a fixed number. Even though s++ will be quicker to execute than s = s + 1, the time difference between these 2 different methods will be the same. I tried the following code:

    int s = 1;
    s++;

And it gave the following compilation and execution time:

Compilation time: 0.32 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0,46 sec

Following that, I tried the code below:

    int s = 1;
    s = s + 1;

And it gave the following execution time:

Compilation time: 0.32 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0,46 sec

So, just as I said, there's no significant difference between the 2 operations as they in themselves are quite simple. A time difference does exist; however, the execution time given above was not so specific, meaning that there must be a time difference that is >0.001, Maaking it pretty much negligible. Hope this answers your question.

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
  • If you compiled with optimization enabled, constant propagation would make both equivalent to `int s = 2;` (and optimize that away if you didn't do anything else with it). If you compiled with optimization disabled, your results are meaningless (and probably bottlenecked on latency of a loop counter in memory, not whatever asm was emitted for these statements). Benchmarking with `-O0` does not provide insight into performance at `-O3`, for micro-optimization things like this. [C loop optimization help for final assignment](https://stackoverflow.com/a/32001196). – Peter Cordes Oct 27 '18 at 17:22
0

++ is more powerful. you can do things like that

if(a++ > 7) b=0;