std::vector 和 llvm::SmallVector 有什么区别?什么时候使用哪一个?
What is the difference between std::vector and llvm::SmallVector? which one to use when?
我想了解 SmallVector
容器在 LLVM 中的使用。我认为 std::vector
可以用来代替小矢量。另外,如果我们在 llvm::SmallVector
中压入的元素多于它的大小会怎样?
What is the difference between std::vector and LLVM::SmallVector?
我假设您熟悉标准向量。 llvm::SmallVector 文档中有描述:
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
It contains some number of elements in-place, which allows it to avoid heap allocation when the actual number of elements is below that threshold. This allows normal "small" cases to be fast without losing generality for large inputs.
Note that this does not attempt to be exception safe.
which one to use when?
在以下情况下使用 std::vector:
- 您需要异常安全或
- 您不想要标准库之外的额外依赖项或者
- 容器不是瓶颈或者
- 性能根本不重要或者
- 向量无论如何都会很大,所以优化不会产生影响
在
时使用small-optimized实现(例如llvm::SmallVector或其他实现)
以上- None适用
Also what happens if we push more elements in llvm::SmallVector than its size?
当内部小缓冲区耗尽时,将分配一个动态缓冲区,其行为类似于std::vector
。
llvm::SmallVector
是为小型数组优化的向量。这种优化来自于不为有限数量的元素执行堆分配。
如果您添加的元素多于描述的使用自动存储分配的元素,它将回退到 std::vector
的行为并分配越来越大的数组。
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 可以在您知道您将始终拥有少量元素并且不会 运行 进入堆分配时获得性能优势。这种性能优势是以异常安全性和对 llvm 库的依赖性为代价的。
我想了解 SmallVector
容器在 LLVM 中的使用。我认为 std::vector
可以用来代替小矢量。另外,如果我们在 llvm::SmallVector
中压入的元素多于它的大小会怎样?
What is the difference between std::vector and LLVM::SmallVector?
我假设您熟悉标准向量。 llvm::SmallVector 文档中有描述:
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
It contains some number of elements in-place, which allows it to avoid heap allocation when the actual number of elements is below that threshold. This allows normal "small" cases to be fast without losing generality for large inputs.
Note that this does not attempt to be exception safe.
which one to use when?
在以下情况下使用 std::vector:
- 您需要异常安全或
- 您不想要标准库之外的额外依赖项或者
- 容器不是瓶颈或者
- 性能根本不重要或者
- 向量无论如何都会很大,所以优化不会产生影响
在
时使用small-optimized实现(例如llvm::SmallVector或其他实现)-
以上
- None适用
Also what happens if we push more elements in llvm::SmallVector than its size?
当内部小缓冲区耗尽时,将分配一个动态缓冲区,其行为类似于std::vector
。
llvm::SmallVector
是为小型数组优化的向量。这种优化来自于不为有限数量的元素执行堆分配。
如果您添加的元素多于描述的使用自动存储分配的元素,它将回退到 std::vector
的行为并分配越来越大的数组。
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 可以在您知道您将始终拥有少量元素并且不会 运行 进入堆分配时获得性能优势。这种性能优势是以异常安全性和对 llvm 库的依赖性为代价的。