简体   繁体   中英

c++ std::vector<> vs new[] performance

当两者都固定且长度相同时, std::vector<>new[]之间的分配,释放和访问时间是否有很大差异?

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).

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM