Efficient C Tips #3 – Avoiding post increment / decrement

来源:互联网 发布:西安java工程师招聘 编辑:程序博客网 时间:2024/06/07 16:00

     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.

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