How the performance of boost::array
compares to that of std::vector
, and which factors have significant influence on it?
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.
That's about 3 - 4 times slower!
Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits.
boost::array
(or C++0x's std::array
) should be faster than std::vector
because boost::array
instances are entirely on the stack. This means boost::array
has no heap allocation, and it also means it can't grow past the size you specify for it at construction.
The purpose of boost::array
is to serve as a thin layer around primitive arrays, so you can treat them as standard containers with .begin()
, .end()
etc. Good compilers should eliminate all overhead of boost::array
such that it performs identically to primitive arrays.
All this concerning "default" setup, where you don't have custom allocators and you measure simple things like array construction, access and modification of elements. On the other hand, things can turn around in other tests, other platforms or with a clever setup. For example,
std::vector
might not any more be all that expensive.std::vector
with another is normally a very fast operation; the speed of swapping two pointers. Swapping two boost::array
instances might be much more expensive; in the order of copying n
elements. But then, in C++0x, of which std::array
will be a part, swapping two arrays will be fast again, thanks to rvalue references and their move semantics.boost::array
might require copying each array element. Then again, sometimes copying any object is very fast, even faster than copying a pointer and even in your C++03 compiler -- thanks to copy elision.You can profile to see which is faster for your use, but even this test will only give you an idea for a particular version of a particular compiler on a particular platform.
The best way to reach any conclusion is writing programs to test their performance with huge amount of data. How else one can arrive at any conclusion?
While you're at it, you may need some tools to assist you, such as VTune, or AMD CodeAnalyst Performance Analyzer, etc. Very Sleepy (free tool) is a C/C++ CPU profiler for Windows systems. You may try them!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With