一直想知道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