Possible Duplicate:
std::vector is so much slower than plain arrays?
Looks like vector is allocated on heap instead of stack.
So should I consider using array to replace vector (if possible) when performance becomes a serious issue?
Possible Duplicate:
std::vector is so much slower than plain arrays?
Looks like vector is allocated on heap instead of stack.
So should I consider using array to replace vector (if possible) when performance becomes a serious issue?
No. (to satisfy the comment pedants, no, you should not "prefer" arrays over vectors for performance, but sure, you should "consider" using arrays to replace vectors, for the specific cases outlined below)
When performance becomes a serious issue, you should base your optimizations on actual data, not second-hand stories and hearsay and superstition.
If replacing your vector with an array gives you a measurable (and necessary) speedup, then you should do it.
But note that you can only use a stack-allocated array if:
In most cases, these conditions won't be true, and then the array would have to be heap-allocated anyway, and then you just lost the one advantage arrays had.
But if all those conditions are true and you can see that this heap allocation is actually hurting your performance measurably, then yes, switching to an array (or a std::array
) makes sense.
Otherwise? No...
If the number of elements is known in advance, in coding-time, then yes, you should prefer using array. C++11 provides this:
std::array<int,10000> arr;
But avoid using this:
int arr[10000]; //avoid it in C++11 (strictly), and possibly in C++03 also!
In C++03, you should still prefer std::vector
in most of the cases (unless experiments show it is slow):
std::vector<int> arr;
arr.reserve(10000); //it is good if you know the (min) number of items!
In most cases, when vector appears to be slow, it is because programmers don't take advantage of reserve()
function. Instead they rely on the repeated allocation-deallocation-copy strategy, when the vector resizes itself.
Unless you're running on an exceptional system (i.e. one with a slow memory allocator) it is unlikely to make a significant difference. I'd suggest you prefer using std::vector instead, for its better type safety than plain arrays.