How to improve the performance of C++ Application

==影响性能的常见因素==
* 访问/读写慢速的磁盘,网络设备或外部设备
* 频繁的new/delete对象,尤其是复杂的大对象
* 频繁的函数调用也会带来性能上的开销
* 频繁的创建进程/线程,以及数据库/网络连接
* 不合适的数据结构和低效的算法

==针对这些因素的相应解决方法==
* 使用内部缓存以减少读取外设的次数,将读写外设的操作放到单独的线程中
* 使用内存池或其他内存优化策略, 并尽量多使用引用或指针,以减少临时对象的产生
* 可以使用内联函数或宏提高性能,并限制不必要的虚拟函数
* 使用进程池/线程池/连接池
* 针对不同的应用场合,采用相宜的数据结构和算法

==理论篇==

Effective C++

Effcient C++

The art of computer programming

==实践篇==
* 找出影响性能的瓶颈
* 通过测试得到性能的相关数据
* 不断的尝试修改,测试,观察,分析

//as the below example, we can find
//++i is better than i++
//a+=b is better than a=a+b

class CProduct
{
     friend const CProduct operator+(const CProduct& lhs,const CProduct& rhs);
public:
CProduct(int price);
     CProduct(const CProduct& rhs);

virtual ~CProduct();
     operator==(const CProduct& rhs) ;
   
     CProduct& operator=(const CProduct& rhs);
     CProduct& operator+=(const CProduct& rhs);
     CProduct& operator++();
     CProduct operator++(int);
private:
     int m_nPrice;

};


CProduct::CProduct(int price):m_nPrice(price)
{

}

CProduct::~CProduct()
{

}

CProduct::CProduct(const CProduct& rhs):m_nPrice(rhs.m_nPrice)
{

}

CProduct& CProduct::operator=(const CProduct& rhs)
{
     if(this==&rhs)
         return *this;
     m_nPrice=rhs.m_nPrice;
     return *this;
}

const CProduct operator+(const CProduct& lhs,const CProduct& rhs)
{
     return CProduct(lhs.m_nPrice+rhs.m_nPrice);
}

CProduct& CProduct::operator+=(const CProduct& rhs)
{
     m_nPrice+=rhs.m_nPrice;
     return *this;
}

CProduct& CProduct::operator++()//prefix
{
     ++m_nPrice;
     return *this;
}

CProduct CProduct::operator++(int)
{
     CProduct tmp(*this);
     ++(*this);
     return tmp;
}
posted @ 2009-08-20 20:38  寻道  阅读(161)  评论(0)    收藏  举报