Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between std::vector and llvm::SmallVector? which one to use when?

Tags:

c++

stl

vector

llvm

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?

like image 535
user1669844 Avatar asked Feb 08 '17 19:02

user1669844


People also ask

What is the difference between std :: array and std :: vector?

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.

What is small vector?

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.


1 Answers

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.

like image 126
lcs Avatar answered Oct 05 '22 23:10

lcs