Efficient C Tips #3 – Avoiding post increment / decrement

50 篇文章 1 订阅

     by Nigel Jones

        原文地址: http://embeddedgurus.com/stack-overflow/2008/08/efficient-c-tips-3-avoiding-post-increment-decrement/

        It always seems counter intuitive to me,  but post increment / decrement(后缀自增/自减) operations in C / C++ often result in inefficient code,  particularly when de-referencing(解引用) pointers.  For example

for (i = 0, ptr = buffer; i < 8; i++)
{
 *ptr++ = i;
}

This code snippet contains two post increment operations.  With most compilers,  you’ll get better code quality by re-writing it like this:

for (i = 0, ptr = buffer; i < 8; ++i)
{
 *ptr = i;
 ++ptr;
}

        Why is this you ask? Well,  the best explanation I’ve come across to date is this one on the IAR website:

        Certainly taking the time to understand what’s going on is worthwhile. However,  if it makes your head hurt then just remember to avoid post increment / decrement operations.

        Incidentally,  you may find that on your particular target it makes no difference.  However,  this is purely a result of the fact that your target processor directly  supports the required addressing modes to make post increments efficient.  If you are interested in writing code that is universally efficient,  then avoid the use of post increment / decrement.

        You may also wonder just how much this saves you.  I’ve run some tests on various compilers / targets and have found that this coding style cuts the object code size down from zero to several percent.  I’ve never seen it increase the code size.  More to the point,  in loops,  using a pre-increment(前置增量) can save you a load / store operation per increment per loop iteration. These can add up to some serious time savings.

     // 下方评论也很精彩, 不转了!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值