之前在做acm的一道兩路合併排序時一直運行超時,原因就在於我習慣使用vector來存儲數據。而vector和動態數組在效率上是存在區別的,所以在這裏就討論一下兩者的效率。
從網上資料看在vs中debug和release模式下vector的運行時間存在差別,而對於數組 而言沒有變化,且總的來說數組效率高於vector。對於stl而言不同的編譯器效果不同,下面都是用vs2010進行測試。
Debug模式下的測試結果是:
基本上vector的運行時間是動態數組的50倍左右。
Release模式下的測試結果是:
vector的運行時間是動態數組的兩倍左右。且相比debug模式下運行時間均有顯著提高。
結論:至少在vs2010中vector的運行效率是低於動態數組的。因此在對效率要求較高的情況下建議使用動態數組。
附測試代碼:
#include<iostream>
#include<ctime>
#include <vector>
using namespace std;
int main()
{
vector<int> vtest;
int *test;
int n,tmp;
long start,end;
while(cin>>n)
{
test=new int[n];
start=clock();
for(int i=0;i<n;++i)
{
vtest.push_back(i);
}
for(int i=0;i<n;++i)
{
tmp=vtest[i];
}
end=clock();
cout<<"vector運行耗時"<<endl;
cout << end-start <<endl;
start=clock();
for(int i=0;i<n;++i)
{
test[i]=i;
}
for(int i=0;i<n;++i)
{
tmp=test[i];
}
end=clock();
cout<<"動態數組運行耗時"<<endl;
cout << end-start <<endl;
}
return 0;
}