int i=0;
a[i] =3;
i++;
Vs
int i=0;
a[i++]=3;
Is it just a fancy way of writing code and saving lines or you really do improve the performance here?
int i=0;
a[i] =3;
i++;
Vs
int i=0;
a[i++]=3;
Is it just a fancy way of writing code and saving lines or you really do improve the performance here?
Using https://godbolt.org/, GCC with optimisations enabled generates the same code for both cases.
main:
sub rsp, 8
mov esi, 3
mov edi, OFFSET FLAT:std::cout
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
xor eax, eax
add rsp, 8
ret
_GLOBAL__sub_I_main:
sub rsp, 8
mov edi, OFFSET FLAT:std::__ioinit
call std::ios_base::Init::Init()
mov edx, OFFSET FLAT:__dso_handle
mov esi, OFFSET FLAT:std::__ioinit
mov edi, OFFSET FLAT:std::ios_base::Init::~Init()
add rsp, 8
jmp __cxa_atexit
Note: gcc has optimised std::cout << a[0] to std::cout<<3
There's no difference other than a[i++]=3; being more dangerous, since mixing the ++ operators with other operators in the same expression is not a good idea.
See Why are these constructs (using ++) undefined behavior in C? for examples of when this could be dangerous.
Sources: MISRA-C:2012 rule 13.3 et al, see this. The wording in the latest MISRA is that ++ should not be used in an expression with other side effects.
Both segments of code, on their own, would have negligible differences in performance. In practice, both formats would probably be optimized out to the same performance level by the compiler. Placing both inside a loop where i goes from 0 to a million, the difference in runtime was a few ms that averaged out to be negligible.
In theory (taking the code at face value with a very naive compiler) the second snippet is faster because of multiple reads to i in the first one..
BUT having said that, in practice it's always 100% the same as the compiler will always optimise both out.
Side note: Stop thinking about these micro optimisations and let the compiler figure it out.