~Onlooker 2008-08-24 06:48 采纳率: 0%
浏览 416
已采纳

在 c 语言中 i + + 和 + + i 之间有性能差异吗?

Is there a performance difference between i++ and ++i if the resulting value is not used?

转载于:https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i-in-c

  • 写回答

13条回答 默认 最新

  • 叼花硬汉 2008-08-24 06:48
    关注

    Executive summary: No.

    i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away.

    We can demonstrate this by looking at the code for this function, both with ++i and i++.

    $ cat i++.c
    extern void g(int i);
    void f()
    {
        int i;
    
        for (i = 0; i < 100; i++)
            g(i);
    
    }
    

    The files are the same, except for ++i and i++:

    $ diff i++.c ++i.c
    6c6
    <     for (i = 0; i < 100; i++)
    ---
    >     for (i = 0; i < 100; ++i)
    

    We'll compile them, and also get the generated assembler:

    $ gcc -c i++.c ++i.c
    $ gcc -S i++.c ++i.c
    

    And we can see that both the generated object and assembler files are the same.

    $ md5 i++.s ++i.s
    MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
    MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e
    
    $ md5 *.o
    MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
    MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突