Optimize code


1. 用 for (i = n-1; i >= 0; –i) 不用 for (i = 0; i < n; i++) 与0比较的效率高,–i的效率比i–的效率高;check http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.15 可以知道为什么++i 比 i++ 更有效率;

2. 使用Int,因为计算机目前大多是32位的;

3. 将local functions声明成static, e.g.,
           static void fun()

4.  对c++来说使用 ‘op=’ ,比如,使用
           myClass += value;
           myClass = myClass + value;
第2种情况会产生一个temporary object;

5. 尽量使用inline函数,如果不在意生成的可执行程序的大小

6. 尽量去掉for loop,尽管这样会增加代码量;如果不行,可以尽量使用while语句来替代for语句;

7. 使用“引用”不是“指针”,即:
           int x; 
           void Ptr(const int* p) { x += *p; }
           void Ref(const int& p) { x += p; }        // good
           a. There’s no need to check that the reference is not NULL. References are never NULL. (Creating a NULL reference is possible, but difficult). 
           b. References don’t require the * dereference operator. Less typing. Cleaner code.
           c. There’s the opportunity for greater efficiency with references. A major challenge for compiler writers is producing high-performance code with pointers. Pointers make it extremely difficult for a compiler to know when different variables refer to the same location, which prevents the compiler from generating the fastest possible code. Since a variable reference points to the same location during its entire life, a C++ compiler can do a better job of optimization than it can with pointer-based code. There’s no guarantee that your compiler will do a better job at optimization, but it might.



1. 将发生概率大的case放到switch语句的前面;


1 thought on “Optimize code

  1. Feng

    "Frequently copied objects with expensive constructors and destructors can be serious bottlenecks." 我的IBVH的一个bottleneck就是非常非常频繁的调用Point类的析构函数。


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s