

There are, of course, a number of possibilities and use cases: Benchmarks and use casesĪs usual, when creating small benchmarks, the overall goal should be gaining insight, and the example should be motivated by our particular use case. We will compare all these options in a simple test case, to see if there is any difference.

Interestingly, this has an important impact on performance. This can be done with any type of vector or array. Of course, another way to use memory is to pre-allocate a chuck of memory, and then reuse it. While using the stack is generally faster (and we will see by how much), it is also the cause of bugs and security risks (the infamous stack overflow). In contrast, std::vector will normally be allocated on the heap by default. While the C++ standard doesn’t allow this, most compilers offer VLA as an extension to C++. Yet another aspect to have in mind is that memory can be allocated on the stack or on the heap, which can impact performance to some extent.Īllocating on the stack is easier with C, as since C99, C supports variable-length arrays (VLA) which are stack-allocated. For example, when constructing a std::vector without reserve, due to copying of its elements when exceeding its capacity, as we shall verify, they can be indeed be orders of magnitude slower than a raw array. As such, are more prone to being misused.

Standard vectors are also more flexible, enabling dynamic memory management. This is actually an interesting feature of std::vector, as using them will save you time debugging run-time errors, and when compiled with optimization flags, these checks do not take place. However, std::vector will also do some sanity checks, especially when compiled in debug mode, which will have an associated cost. Some differences between std::vector and arraysīefore diving into some benchmarks, let’s discuss some of the fundamental differences between C++ vectors and C arrays.Īccording to the C++ standard, std::vector is implemented as a combination of two stack pointers and a plain array. Well, as we shall see, a lot depends on how are you using these vectors or arrays. While there is no doubt that std::vector is easier to use and offers important safety guarantees, it’s not obvious that we can always obtain an optimal performance using standard vectors, as usually there is a trade-off between abstraction and performance.Īccording to the general wisdom, however, std::vector is an array under the hood, and the compiler should be smart enough to optimize out all extra abstraction and make them as fast as raw arrays.īut… is this true? Is the compiler that smart? In C++, there are several options to store a sequence of values, but the most common options are std:vector and C-style arrays.
