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

前端 未结 17 2041
臣服心动
臣服心动 2020-11-21 17:15

We have the question is there a performance difference between i++ and ++i in C?

What\'s the answer for C++?

17条回答
  •  独厮守ぢ
    2020-11-21 18:17

    It's not entirely correct to say that the compiler can't optimize away the temporary variable copy in the postfix case. A quick test with VC shows that it, at least, can do that in certain cases.

    In the following example, the code generated is identical for prefix and postfix, for instance:

    #include 
    
    class Foo
    {
    public:
    
        Foo() { myData=0; }
        Foo(const Foo &rhs) { myData=rhs.myData; }
    
        const Foo& operator++()
        {
            this->myData++;
            return *this;
        }
    
        const Foo operator++(int)
        {
            Foo tmp(*this);
            this->myData++;
            return tmp;
        }
    
        int GetData() { return myData; }
    
    private:
    
        int myData;
    };
    
    int main(int argc, char* argv[])
    {
        Foo testFoo;
    
        int count;
        printf("Enter loop count: ");
        scanf("%d", &count);
    
        for(int i=0; i

    Whether you do ++testFoo or testFoo++, you'll still get the same resulting code. In fact, without reading the count in from the user, the optimizer got the whole thing down to a constant. So this:

    for(int i=0; i<10; i++)
    {
        testFoo++;
    }
    
    printf("Value: %d\n", testFoo.GetData());
    

    Resulted in the following:

    00401000  push        0Ah  
    00401002  push        offset string "Value: %d\n" (402104h) 
    00401007  call        dword ptr [__imp__printf (4020A0h)] 
    

    So while it's certainly the case that the postfix version could be slower, it may well be that the optimizer will be good enough to get rid of the temporary copy if you're not using it.

提交回复
热议问题