i++ less efficient than ++i, how to show this?

前端 未结 9 1867
暖寄归人
暖寄归人 2020-12-03 14:30

I am trying to show by example that the prefix increment is more efficient than the postfix increment.

In theory this makes sense: i++ needs to be able to return the

9条回答
  •  长情又很酷
    2020-12-03 14:46

    Ok, all this prefix/postfix "optimization" is just... some big misunderstanding.

    The major idea that i++ returns its original copy and thus requires copying the value.

    This may be correct for some unefficient implementations of iterators. However in 99% of cases even with STL iterators there is no difference because compiler knows how to optimize it and the actual iterators are just pointers that look like class. And of course there is no difference for primitive types like integers on pointers.

    So... forget about it.

    EDIT: Clearification

    As I had mentioned, most of STL iterator classes are just pointers wrapped with classes, that have all member functions inlined allowing out-optimization of such irrelevant copy.

    And yes, if you have your own iterators without inlined member functions, then it may work slower. But, you should just understand what compiler does and what does not.

    As a small prove, take this code:

    int sum1(vector const &v)
    {
        int n;
        for(auto x=v.begin();x!=v.end();x++)
                n+=*x;
        return n;
    }
    
    int sum2(vector const &v)
    {
        int n;
        for(auto x=v.begin();x!=v.end();++x)
                n+=*x;
        return n;
    }
    
    int sum3(set const &v)
    {
        int n;
        for(auto x=v.begin();x!=v.end();x++)
                n+=*x;
        return n;
    }
    
    int sum4(set const &v)
    {
        int n;
        for(auto x=v.begin();x!=v.end();++x)
                n+=*x;
        return n;
    }
    

    Compile it to assembly and compare sum1 and sum2, sum3 and sum4...

    I just can tell you... gcc give exactly the same code with -02.

提交回复
热议问题