記得以前在一本書上看過boost::shared_ptr的回帶來一定的效率損失,但是并不大.今天閑來無事,編譯了一個(gè)BOOST并簡(jiǎn)單測(cè)試了一下,看看到底有多少性能損失.測(cè)試代碼和結(jié)果如下:
比較函數(shù)
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結(jié)果:
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;
}
指針結(jié)果:
937
938
954
953
953
執(zhí)行速度已經(jīng)相差一倍了.自動(dòng)內(nèi)存管理的代價(jià)啊!~~~~
環(huán)境:Q8200 2.33GHZ 4G內(nèi)存
以上只是簡(jiǎn)單的測(cè)試,僅拱參考
補(bǔ)充說明:
很多朋友流言說在MAP中存放string*沒有意義。可是我上一個(gè)項(xiàng)目就需要這么做。
試想我現(xiàn)在有10篇文檔,現(xiàn)在需要統(tǒng)計(jì)每篇文檔當(dāng)中每個(gè)字出現(xiàn)的次數(shù),還需要統(tǒng)計(jì)全部文章中全部字出現(xiàn)的次數(shù)。為了保證效率,應(yīng)當(dāng)保證每個(gè)字在內(nèi)存當(dāng)中只留一份拷貝(因?yàn)橐院笥锌赡芙y(tǒng)計(jì)每個(gè)詞,甚至每句話出現(xiàn)的次數(shù))。要實(shí)現(xiàn)這個(gè)功能,是否還有更好的算法?
還有朋友流言說指針版沒有銷毀string指針。可是在這個(gè)程序中執(zhí)行cout<<GetTickCount() - oldtime <<endl;之前shared_ptr也沒有釋放資源。所以資源的釋放不會(huì)造成誤差。
luck朋友的方法最為有效,把比較函數(shù)變成:
bool operator() (const T &lh,const T &rh) const
{
return *lh<*rh;
}
下面是shared_ptr執(zhí)行5次的時(shí)間:
968
969
985
969
969
下面是string*執(zhí)行5次的時(shí)間:
859
875
860
859
860
看來即使是小對(duì)象也不能放松!當(dāng)很多小對(duì)象發(fā)生構(gòu)造和析構(gòu)時(shí)所耗費(fèi)的時(shí)間還是不容小視的!~