Efficiency Comparison Between std vector and std list

Source: Internet
Author: User

I always wanted to know which efficiency is higher for vector and list in std. Therefore, a simple test was conducted to compare the efficiency of the push_back and traversal operations of std vector and list. Result 1: 1. push_back operation: 100000 elements are operated continuously by push_back, and then clear (). It has been repeated for 10000 times. The vector takes 13 s, and the list takes 118 s. 2. traversal operation: The iterator is used to traverse the vector and list of 100000 elements, traversing 10000 times. Vector takes 20 s, and list takes 15 s. If an ordered element is added, the efficiency of vector is nearly 10 times higher than that of list, when an iterator is used to traverse elements, the efficiency is not much different. Code: [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-s Tart <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;} output: vector spend time 13 list spend time 118 vector spend time 20 list spend time 15

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.