mona
mona

Reputation: 123

which function is faster push_back, insert in C++

I need to insert onto the end of a vector, 2 elements each time.

I was wondering whether doing vector.insert( iter_first, iter_second) is faster than doing vector.push_back( first ) then vector.push_back( second )?

Maybe another alternative would be to create a struct like this:

struct T{int a; int b;};
T t;
t.a = first;
t.b = second;
X.push_back(t);

Upvotes: 3

Views: 3725

Answers (4)

James Kanze
James Kanze

Reputation: 153899

Practically speaking, push_back will call insert, so calling push_back twice ends up calling insert twice. In practice, however, if the code has been optimized, I'd be surprised if it made a difference. Do what's logical, and optimize later if you have performance problems.

Upvotes: 0

Raymond Chen
Raymond Chen

Reputation: 45173

While in your case the difference is insignificant, in general the C++ language standard specifies complexity information, so you don't need to ask - you can just look it up. vector::push_back has amortized constant time complexity, and vector::insert is either proportional to the sum of the number of elements inserted and the number of elements moved, or the product of the two, depending on how you call it.

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81916

Inserting at the end of a vector will be much faster than inserting at the middle or beginning of a vector.

This will only matter when you have a Large vector, and/or the copy constructors of your objects are Incredibly painful.

Upvotes: 0

Mark B
Mark B

Reputation: 96233

If the two elements are logically related, then you would use a struct or class. If they're unrelated then certainly don't group them for performance reasons.

This smells of premature optimization. Instead, write the code that's clearest to maintain and let the compiler generate the code for you. That's what it's there for. Consider that code that's easy to read is easy to maintain, and code that's easy to maintain is easy to refactor and less likely to have subtle performance bugs due to misunderstandings.

Upvotes: 6

Related Questions