記得以前在一本書上看過boost::shared_ptr的回帶來一定的效率損失,但是并不大.今天閑來無事,編譯了一個BOOST并簡單測試了一下,看看到底有多少性能損失.測試代碼和結果如下:
比較函數
template <class T>
class compareP
{
public:
bool operator() (const T lh,const T rh) const
{
return *lh<*rh;
}
};
boost:
int _tmain(int argc, _TCHAR* argv[])
{
DWORD oldtime = GetTickCount();
typedef map<boost::shared_ptr<string>,size_t,compareP<boost::shared_ptr<string> > > container_type;
typedef container_type::iterator iterator;
container_type container;
for (size_t i(0) ; i<500000 ; ++i)
{
boost::shared_ptr<string> pstr(new string);
char buffer[32];
*pstr = itoa(i,buffer,10);
container[pstr]=0;
}
cout<<GetTickCount() - oldtime <<endl;
return EXIT_SUCCESS;
}
boost結果:
2000
2015
2015
2016
2017
指針:
int _tmain(int argc, _TCHAR* argv[])
{
DWORD oldtime = GetTickCount();
typedef map<string*,size_t,compareP<string*> > container_type;
typedef container_type::iterator iterator;
container_type container;
for (size_t i(0) ; i<500000 ; ++i)
{
string *pstr = new string;
char buffer[32];
*pstr = itoa(i,buffer,10);
container[pstr]=0;
}
cout<<GetTickCount() - oldtime <<endl;
return EXIT_SUCCESS;
}
指針結果:
937
938
954
953
953
執行速度已經相差一倍了.自動內存管理的代價啊!~~~~
環境:Q8200 2.33GHZ 4G內存
以上只是簡單的測試,僅拱參考
補充說明:
很多朋友流言說在MAP中存放string*沒有意義??墒俏疑弦粋€項目就需要這么做。
試想我現在有10篇文檔,現在需要統計每篇文檔當中每個字出現的次數,還需要統計全部文章中全部字出現的次數。為了保證效率,應當保證每個字在內存當中只留一份拷貝(因為以后有可能統計每個詞,甚至每句話出現的次數)。要實現這個功能,是否還有更好的算法?
還有朋友流言說指針版沒有銷毀string指針。可是在這個程序中執行cout<<GetTickCount() - oldtime <<endl;之前shared_ptr也沒有釋放資源。所以資源的釋放不會造成誤差。
luck朋友的方法最為有效,把比較函數變成:
bool operator() (const T &lh,const T &rh) const
{
return *lh<*rh;
}
下面是shared_ptr執行5次的時間:
968
969
985
969
969
下面是string*執行5次的時間:
859
875
860
859
860
看來即使是小對象也不能放松!當很多小對象發生構造和析構時所耗費的時間還是不容小視的!~