Difference in performance when vector: resize () uses array index and vector: Reserve () uses push_back ()

Source: Internet
Author: User

For vector usage, the additional time consumed by copying data to prevent reallocate memory.

The following two combinations can be used to prevent reallocate.

1. Vector: resize () using array index

2. Vector: Reserve () Use push_back ().


So I tested these two cases on the Windows 2003 platform, and compared them with 3 in which push_back () is directly used without memory reservation:

# Deprecision Max 100000000
Void testpushback ()
Clock_t start = clock ();
Vector <int> C;
// A. Reserve (max );
For (INT I = 0; I <Max; I ++)
C. push_back (I );

Cout <clock ()-start <Endl;
Cout <C. Size () <"" <C. Capacity () <Endl;

Start = clock ();
Vector <int>;
A. Reserve (max );
For (INT I = 0; I <Max; I ++)
A. push_back (I );

Cout <clock ()-start <Endl;
Cout <A. Size () <"" <A. Capacity () <Endl;

Start = clock ();
Vector <int> B;
B. Resize (max );
For (INT I = 0; I <Max; I ++)
B [I] = I;
Cout <clock ()-start <Endl;
Cout <B. Size () <''<B. Capacity () <Endl;

The test results are as follows:


18859100000000 13621656718172100000000 1000000003313100000000 press any key to continue...

It is found that the combination of reserve and push_back () on window2003 is similar to that of direct push_back,

The combination of resize () and array index has great performance advantages.


PS. Later, the same test was performed on the Linux rh64 platform.

The test result is exactly the opposite to that in window2003. The combination of resize () and array index takes a longer time than the other two.


It seems that the implementation of the platform is quite different.


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.