Reputation: 2423
Is there any big difference in allocation, deallocation and access time between std::vector<>
and new[]
when both are fixed and same length?
Upvotes: 3
Views: 2218
Reputation: 477358
new
is a bad thing, because it violates the idiom of single responsibility by assuming two responsibilities: Storage allocation and object construction. Complexity is the enemy of sanity, and you fight complexity by separating concerns and isolating responsibilities.
The standard library containers allow you to do just that, and only think about objects. Moreover, std::vector
addionally allows you to think about storage, but separately, via the reserve
/capacity
interfaces.
So for the sake of keeping a clear mind about your program logic, you should always prefer a container such as std::vector
:
std::vector<Foo> v;
// make some storage available
v.reserve(100);
// work with objects - no allocation is required
v.push_back(x);
v.push_back(f(1, 2));
v.emplace_back(true, 'a', 10);
Upvotes: 3
Reputation: 279315
Depends on the types and how you call it. std::vector<int> v(1000000);
has to zero a million ints, whereas new int[1000000];
doesn't, so I would expect a difference in speed. This is one place in std::vector
where you might pay through the nose for something you don't use, if for some reason you don't care about the initial values of the elements.
If you compare std::vector<int> v(1000000);
with new int[1000000]();
then I doubt you'll see much difference. The significant question is whether one of them somehow has a more optimized loop setting the zeros, than the other one does. If so, then the implementation of the other one has missed a trick (or more specifically the optimizer has).
Upvotes: 10