Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I remember 15 years ago people were saying the same thing! (not to bother with this micro-optimisation because the compiler will do it anyway).

I often still sometimes write "++it" out of habit, but usually will just go with whichever variant I feel conveys my intent better and leave the optimisation of this to the compiler.

EDIT:

Its also not always true that "++it" is faster than "it++", as this quote from Agner Fog's C++ optimisation guide notes:

    For example, x = array[i++] is more efficient than
    x = array[++i] because in the latter case, the
    calculation of the address of the array element has
    to wait for the new value of i which will delay the
    availability of x for approximately two clock cycles.
    Obviously, the initial value of i must be adjusted
    if you change pre-increment to post-increment.


The example you gave is actually different code and are not directly comparable. With i = 0; x = array[i++] will access the first element, x = array[++i] will access the second element. So of course in the second case the array load will wait until it gets the incremented value.

Edit: The same code with a preincrement notation would be x = array[i]; ++i;


The cited statement accounts for this:

    > Obviously, the initial value of i must be adjusted
    > if you change pre-increment to post-increment.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: