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

前端 未结 9 1836
暖寄归人
暖寄归人 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:52

    Try to use while or do something with returned value, e.g.:

    #define SOME_BIG_CONSTANT 1000000000
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int i = 1;
        int d = 0;
    
        DWORD d1 = GetTickCount();
        while(i < SOME_BIG_CONSTANT + 1)
        {
            d += i++;
        }
        DWORD t1 = GetTickCount() - d1;
    
        printf("%d", d);
        printf("\ni++ > %d <\n", t1);
    
        i = 0;
        d = 0;
    
        d1 = GetTickCount();
        while(i < SOME_BIG_CONSTANT)
        {
            d += ++i;
    
        }
        t1 = GetTickCount() - d1;
    
        printf("%d", d);
        printf("\n++i > %d <\n", t1);
    
        return 0;
    }
    

    Compiled with VS 2005 using /O2 or /Ox, tried on my desktop and on laptop.

    Stably get something around on laptop, on desktop numbers are a bit different (but rate is about the same):

    i++ > 8xx < 
    ++i > 6xx <
    

    xx means that numbers are different e.g. 813 vs 640 - still around 20% speed up.

    And one more point - if you replace "d +=" with "d = " you will see nice optimization trick:

    i++ > 935 <
    ++i > 0 <
    

    However, it's quite specific. But after all, I don't see any reasons to change my mind and think there is no difference :)

提交回复
热议问题