std vector与std list的效率比较
一直想知道std中vector和list的效率哪个高些。
于是做了一个简单的测试,对std vector和list的push_back与遍历操作的效率进行比较。
结果如下:
1. push_back操作:连续push_back操作100000个元素,然后clear()。一直重复10000次。
vector耗时13s, list耗时118s
2. 遍历操作:采用迭代器对100000个元素的vector和list遍历,遍历10000次。
vector耗时20s, list耗时15s
可见,如果是有序的添加元素,vector比list的效率要高将近10倍,而采用迭代器遍历元素时则效率相差不大。
附代码:
[cpp]
#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
补充:软件开发 , C++ ,