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

前端 未结 14 849
遥遥无期
遥遥无期 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 11:00

    From Efficiency versus intent by Andrew Koenig :

    First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned.

    And :

    So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.

    So, if the resulting value is not used, I would use ++i. But not because it is more efficient: because it correctly states my intent.

    0 讨论(0)
  • 2020-11-22 11:00

    Taking a leaf from Scott Meyers, More Effective c++ Item 6: Distinguish between prefix and postfix forms of increment and decrement operations.

    The prefix version is always preferred over the postfix in regards to objects, especially in regards to iterators.

    The reason for this if you look at the call pattern of the operators.

    // Prefix
    Integer& Integer::operator++()
    {
        *this += 1;
        return *this;
    }
    
    // Postfix
    const Integer Integer::operator++(int)
    {
        Integer oldValue = *this;
        ++(*this);
        return oldValue;
    }
    

    Looking at this example it is easy to see how the prefix operator will always be more efficient than the postfix. Because of the need for a temporary object in the use of the postfix.

    This is why when you see examples using iterators they always use the prefix version.

    But as you point out for int's there is effectively no difference because of compiler optimisation that can take place.

    0 讨论(0)
提交回复
热议问题