一直想知道std中vector和list的效率哪个高些。
于是做了一个简单的测试,对std vector和list的push_back与遍历操作的效率进行比较。
结果如下:
vector耗时13s, list耗时118s
vector耗时20s, list耗时15s
可见,如果是有序的添加元素,vector比list的效率要高将近10倍,而采用迭代器遍历元素时则效率相差不大。
附代码:
#include <iostream>
#include <vector>
#include <list>
#include <ctime>
using namespace std;
class Message
{
};
int main()
{
vector<Message*> vt;
list<Message*> lt;
Message *msg = new Message();
time_t start = time(NULL);
for (int i = 0; i < 10000; ++i) {
vt.clear();
for (int j = 0; j < 100000; ++j) {
vt.push_back(msg);
}
}
time_t end = time(NULL);
cout << "vector spend time " << end - start << endl;
start = time(NULL);
for (int i = 0; i < 10000; ++i) {
lt.clear();
for (int j = 0; j < 100000; ++j) {
lt.push_back(msg);
}
}
end = time(NULL);
cout << "list spend time " << end - start << endl;
delete msg;
msg = NULL;
start = time(NULL);
for (int i = 0; i < 10000; ++i) {
typeof(vt.begin()) it = vt.begin();
while (it != vt.end()) {
msg = *it;
++it;
}
}
end = time(NULL);
cout << "vector spend time " << end - start << endl;
start = time(NULL);
for (int i = 0; i < 10000; ++i) {
typeof(lt.begin()) it = lt.begin();
while (it != lt.end()) {
msg = *it;
++it;
}
}
end = time(NULL);
cout << "list spend time " << end - start << endl;
return 0;
}
vector spend time 13
list spend time 118
vector spend time 20
list spend time 15