Is there a performance difference between i++ and ++i in C?

前端 未结 14 874
遥遥无期
遥遥无期 2020-11-22 10:08

Is there a performance difference between i++ and ++i if the resulting value is not used?

14条回答
  •  情话喂你
    2020-11-22 10:40

    Here's an additional observation if you're worried about micro optimisation. Decrementing loops can 'possibly' be more efficient than incrementing loops (depending on instruction set architecture e.g. ARM), given:

    for (i = 0; i < 100; i++)
    

    On each loop you you will have one instruction each for:

    1. Adding 1 to i.
    2. Compare whether i is less than a 100.
    3. A conditional branch if i is less than a 100.

    Whereas a decrementing loop:

    for (i = 100; i != 0; i--)
    

    The loop will have an instruction for each of:

    1. Decrement i, setting the CPU register status flag.
    2. A conditional branch depending on CPU register status (Z==0).

    Of course this works only when decrementing to zero!

    Remembered from the ARM System Developer's Guide.

提交回复
热议问题