Chưa phân loại

C++ Tutorial – STL vector – push_back vs insert

I did a benchmark to compare performance between insert and push_back functions of vector on 100.000 int elements in C++

 

The result is:

push_back: 240ms

insert: 10ms

 

Here is my code:

#include 		// For cout
#include 		// For vector
#include 		// For clock

using namespace std;

int main() {

	const int count = 1000000;
	vector v1;
	vector v2;

	// Insert items for 2 vector
	for (int i = 0; i < count; i++)
	{
		v1.push_back(i);
		v2.push_back(i * 3);
	}

	// Count time
	int start = clock();

	// This way takes 240ms
	for (int i = 0; i < count; i++)
	{
		v1.push_back(v2[i]);
	}

	int end = clock();
	cout << "push_back time: " << end - start << endl;

	start = clock();

	// This way take 10ms
	v1.insert(v1.end(), v2.begin(), v2.end());

	end = clock();
	cout << "insert time: " << end - start << endl;

	cin.get();

	return 0;
}

So, if you want to perform copy items between vectors, you should use insert instead of push_back.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s