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

前端 未结 14 1085
遥遥无期
遥遥无期 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:58

    A better answer is that ++i will sometimes be faster but never slower.

    Everyone seems to be assuming that i is a regular built-in type such as int. In this case there will be no measurable difference.

    However if i is complex type then you may well find a measurable difference. For i++ you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with ++it you can just return the final value.

    Foo Foo::operator++()
    {
      Foo oldFoo = *this; // copy existing value - could be slow
      // yadda yadda, do increment
      return oldFoo;
    }
    

    Another difference is that with ++i you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower.

    A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using ++i instead of i++ where the outcome is not affected.

提交回复
热议问题