This is an archive of the discontinued LLVM Phabricator instance.

[CodingStandards] Clarify the recommendation to use SmallVector
AbandonedPublic

Authored by gribozavr on Oct 16 2020, 5:01 AM.

Details

Summary

SmallVector is not unconditionally better than std::vector, it only
makes sense when the small size optimization is meaningful. In fact,
LLVM and Clang use std::vector a lot when the small size optimization is
not needed. Therefore, the wording "should usually be used" is
misleading.

Diff Detail

Event Timeline

gribozavr created this revision.Oct 16 2020, 5:01 AM
Herald added a project: Restricted Project. · View Herald TranscriptOct 16 2020, 5:01 AM
gribozavr requested review of this revision.Oct 16 2020, 5:01 AM

What reasoning was used in the patch that added that wording?
IIRC llvm::SmallVector is better than std::vector also because
former doubles the allocation size instead of just increasing it.

gribozavr2 added a subscriber: gribozavr2.

What reasoning was used in the patch that added that wording?

https://reviews.llvm.org/D74340

IIRC llvm::SmallVector is better than std::vector also because
former doubles the allocation size instead of just increasing it.

std::vector must also use a multiplicative strategy in order to provide O(1) push_back. The C++ standard does not guarantee the specific factor though.

As written, the wording can be read to suggest to use llvm::SmallVector<T, 0> instead of std::vector<T>. Is that the intent?

Ratio in llvm-core, not that this method is actually accurate but I guess the ballpark is right:

ag SmallVector llvm/lib | wc
   9498   43412  970112

ag 'std::vector' llvm/lib | wc
   2296    9660  231768

Maybe some examples?

Prefer llvm::SmallVector<T, 10> over std::vector<T> if you expect to store less than 10 elements.

Prefer std::vector<T> over llvm::SmallVector<T, 10> if expect to store way more than 10 elements.

llvm::SmallVector isn't, like, otherwise worse than std::vector, so that you should only consider it over std::vector when the inline-capacity optimization is highly valuable. It does have some specific drawbacks, but we go into this in more detail in the programmer's manual. I think "prefer llvm::SmallVector" is fine general advice for this paragraph.

Even if we decide to change that recommendation, this is not the place to elaborate on the advice. We have an entire section of the developer's manual dedicated to providing guidance on choosing data structures, and we should not duplicate it clumsily and in part out here.

gribozavr abandoned this revision.Jul 31 2022, 8:20 AM
Herald added a project: Restricted Project. · View Herald TranscriptJul 31 2022, 8:20 AM