hurriedly% 2008-08-24 06:48 采纳率: 100%
浏览 420
已采纳

在 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 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解