I am trying to understand the use of SmallVector
container in LLVM. I think std::vector
can be used in place of small vector. Also what happens if we push more elements in llvm::SmallVector
than its size?
Difference between std::vector and std::array in C++Vector is a sequential container to store elements and not index based. Array stores a fixed-size sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so, size increases with insertion of elements.
small_vector is a vector-like container optimized for the case when it contains few elements. It contains some preallocated elements in-place, which can avoid the use of dynamic storage allocation when the actual number of elements is below that preallocated threshold.
llvm::SmallVector
is a vector optimized for small arrays. This optimization comes from not performing heap allocations for a limited number of elements.
In the event that you add more elements than are described to be allocated using automatic storage it will fall back to the behavior of std::vector
and allocate larger and larger arrays.
llvm::SmallVector<int, 10> smallVector;
for(int i = 0; i < 10; i++)
{
smallVector.push_back(i);
}
// No heap allocations have been performed up to this point.
smallVector.push_back(11);
// Only 10 spaces for non heap allocated elements,
// so the push_back above causes a heap allocation.
SmallVector can have a performance benefit when you know you will consistently have a small number of elements and won't run into heap allocations. This performance benefit comes at the cost of exception safety and a dependency on the llvm libraries.
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