Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I prefer array over vector for performance? [duplicate]

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?

like image 807
Deqing Avatar asked Jul 26 '12 08:07

Deqing


1 Answers

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:

  • the size is known at compile-time, and
  • the size is small enough to fit on the stack without causing problems.
  • the size must be fixed, rather than dynamic.

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

like image 143
jalf Avatar answered Sep 28 '22 05:09

jalf