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.
// 下方评论也很精彩, 不转了!
- Efficient C Tips #3 – Avoiding post increment / decrement
- post/pre increment与post/pre decrement的简易理解
- Efficient C Tips #7 – Fast loops
- Efficient C Tips #8 – Use const
- K&R C Bible Increment and Decrement Operators
- increment/decrement/dereference操作符
- increment/decrement/dereference操作符
- Efficient C Tips #1 – Choosing the correct integer size
- Efficient C Tips #2 – Using the optimizer
- Efficient C Tips #4 – Use Speed Optimization
- Efficient C Tips #5 – Make ‘local’ functions ‘static’
- Efficient C Tips #9 – Use lookup tables
- Efficient C Tips #10 – Use unsigned integers
- Overloading the increment and decrement operators (非常好)
- Day7-24.Auto increment and decrement
- Efficient C Tips #6 – Don’t use the ternary operator
- STL源码剖析-increment/decrement/dereference操作符
- STL源码剖析学习之increment、decrement、dereference实现源码
- sharepoint 2007 common IFilters
- 深入理解计算机系统之-虚拟存储4
- cgic: 为C语言编写CGI的C函数库
- 本地调用google地图
- CVE-2012-1823(PHP-CGI RCE)的PoC及技术挑战
- Efficient C Tips #3 – Avoiding post increment / decrement
- jstat 详解
- decrypt[7] Custom Encryption
- value optimized out
- 动态水晶报表:任意表,任意列,以及动态格线
- 数据包 简介
- windbg使用小总结
- wxwidget下连接mysql
- 使用ifstream和getline读取文件内容[c++]