[clang-tools-extra] [clang-tidy] Add performance-inefficient-container-assignment check (PR #222159)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Sep 8 14:48:15 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tools-extra
Author: Andrew Gaul (gaul)
<details>
<summary>Changes</summary>
Finds assignments of a freshly constructed temporary container to a container of the same type, such as `v = std::vector<int>(n, 0);`, and rewrites them to the `assign` member function or an equivalent in-place form that reuses the destination's storage. The temporary allocates its own buffer and the move assignment then discards the one the destination already owns; `assign` writes into the existing buffer and only allocates when the new contents do not fit.
Every rewrite leaves the destination with exactly the elements the assignment would have produced:
```
v = std::vector<int>(n, 0); -> v.assign(n, 0);
v = std::vector<int>(first, last); -> v.assign(first, last);
v = {first, last}; -> v.assign(first, last);
v = std::vector<int>{1, 2, 3}; -> v = {1, 2, 3};
v = std::vector<int>(n); -> v.clear(); v.resize(n);
v = std::vector<int>(other); -> v = other;
s = std::string(p, n); -> s.assign(p, n);
v = std::vector<int>(std::from_range, r); -> v.assign_range(r); (C++23)
```
The multi-argument constructors of the standard sequence containers all have `assign` overloads with the same parameters, so their arguments pass through verbatim. `v = Container()` is not diagnosed because it releases the storage, which `clear()` would keep, and neither is `v = Container(v)`, the idiom for trimming capacity, nor a constructor call with an explicit allocator or a single argument of another type, which is a conversion rather than a copy. The warning is emitted without a fix-it when an argument refers to the destination, when the value of the assignment is used (`assign` returns void), or inside macro expansions; the two-statement `clear(); resize(n);` form is additionally limited to statements of their own whose destination and count have no side effects.
The containers are configurable through the `ContainerClasses` option, which defaults to `std::vector`, `std::deque`, `std::list`, `std::forward_list` and `std::basic_string`; `llvm::SmallVector` follows the same conventions and can be added.
Running the check over the 6,528 llvm, clang and clang-tools-extra translation units of a default build, with `llvm::SmallVector` added to `ContainerClasses`, reports 33 sites and offers a fix-it at 32 of them; the remaining one passes an iterator into the destination. Applying all 32 fix-its and rebuilding the affected translation units compiles cleanly. Typical hits are per-function resets of analysis state such as `TopDownIndex2SU = std::vector<int>(Topo.begin(), Topo.end());` in the AMDGPU scheduler, `Nodes = std::vector<Node>(NodeCount);` in SampleProfileInference, and `Sorted = {Unique.begin(), Unique.end()};` in clangd.
---
Patch is 39.57 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/222159.diff
14 Files Affected:
- (modified) clang-tools-extra/clang-tidy/performance/CMakeLists.txt (+1)
- (added) clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp (+320)
- (added) clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h (+40)
- (modified) clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp (+3)
- (modified) clang-tools-extra/docs/ReleaseNotes.md (+7)
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.md (+1)
- (added) clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md (+89)
- (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/deque (+2)
- (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/forward_list (+2)
- (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/list (+2)
- (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/string (+3)
- (modified) clang-tools-extra/test/clang-tidy/checkers/Inputs/Headers/std/vector (+20)
- (added) clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment-cxx23.cpp (+15)
- (added) clang-tools-extra/test/clang-tidy/checkers/performance/inefficient-container-assignment.cpp (+245)
``````````diff
diff --git a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
index f55a6cf2800f3..31e88acd6c01e 100644
--- a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
@@ -10,6 +10,7 @@ add_clang_library(clangTidyPerformanceModule STATIC
ForRangeCopyCheck.cpp
ImplicitConversionInLoopCheck.cpp
InefficientAlgorithmCheck.cpp
+ InefficientContainerAssignmentCheck.cpp
InefficientStringConcatenationCheck.cpp
InefficientVectorOperationCheck.cpp
MoveConstArgCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp
new file mode 100644
index 0000000000000..ea05e1484a9fe
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.cpp
@@ -0,0 +1,320 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "InefficientContainerAssignmentCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
+#include <optional>
+#include <string>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+namespace {
+
+/// How the assignment can be rewritten without the temporary. The order
+/// matches the %select in the diagnostic.
+enum class Rewrite {
+ Assign, ///< lhs.assign(args...)
+ AssignRange, ///< lhs.assign_range(range)
+ ClearResize, ///< lhs.clear(); lhs.resize(count)
+ InitList, ///< lhs = {...}
+ Direct, ///< lhs = source
+};
+
+} // namespace
+
+/// Collects the variables and members named by \p E so that arguments
+/// referring back to the destination can be detected.
+static void
+collectReferencedDecls(const Expr &E, ASTContext &Ctx,
+ llvm::SmallPtrSetImpl<const ValueDecl *> &Decls) {
+ for (const BoundNodes &N : match(findAll(declRefExpr().bind("ref")), E, Ctx))
+ Decls.insert(N.getNodeAs<DeclRefExpr>("ref")->getDecl());
+ for (const BoundNodes &N :
+ match(findAll(memberExpr().bind("member")), E, Ctx))
+ Decls.insert(N.getNodeAs<MemberExpr>("member")->getMemberDecl());
+}
+
+static bool
+refersToAnyOf(const Expr &E, ASTContext &Ctx,
+ const llvm::SmallPtrSetImpl<const ValueDecl *> &Decls) {
+ llvm::SmallPtrSet<const ValueDecl *, 8> Referenced;
+ collectReferencedDecls(E, Ctx, Referenced);
+ return llvm::any_of(
+ Referenced, [&Decls](const ValueDecl *D) { return Decls.contains(D); });
+}
+
+/// Returns true if one of the first \p NumArgs parameters of \p Ctor has the
+/// type of a template argument of the container other than its element type.
+/// That is what the allocator parameter of the standard containers looks
+/// like, and an explicitly passed allocator has no counterpart in 'assign'.
+static bool passesAllocator(const CXXConstructorDecl &Ctor, unsigned NumArgs,
+ const ASTContext &Ctx) {
+ const auto *Spec =
+ dyn_cast<ClassTemplateSpecializationDecl>(Ctor.getParent());
+ if (!Spec)
+ return false;
+ const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
+ for (unsigned I = 0, E = std::min(NumArgs, Ctor.getNumParams()); I < E; ++I) {
+ const QualType ParamType =
+ Ctor.getParamDecl(I)->getType().getNonReferenceType();
+ if (!ParamType->isRecordType())
+ continue;
+ for (unsigned J = 1; J < TemplateArgs.size(); ++J) {
+ const TemplateArgument &Arg = TemplateArgs[J];
+ if (Arg.getKind() == TemplateArgument::Type &&
+ ASTContext::hasSameUnqualifiedType(Arg.getAsType(), ParamType))
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool isFromRangeTag(QualType T) {
+ const CXXRecordDecl *RD = T.getNonReferenceType()->getAsCXXRecordDecl();
+ return RD && RD->isInStdNamespace() && RD->getName() == "from_range_t";
+}
+
+/// A postfix expression can take a member access directly; anything else has
+/// to be parenthesized first.
+static bool needsParens(const Expr &E) {
+ const Expr *Inner = E.IgnoreImpCasts();
+ if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(Inner))
+ return Call->getOperator() != OO_Subscript &&
+ Call->getOperator() != OO_Call;
+ return !isa<DeclRefExpr, MemberExpr, ArraySubscriptExpr, CallExpr, ParenExpr>(
+ Inner);
+}
+
+/// Returns the statement that directly contains \p E, looking through the
+/// implicit cleanup wrapper and parentheses, or nullptr if \p E is a
+/// subexpression or an initializer.
+static const Stmt *getEnclosingStatement(const Expr &E, ASTContext &Ctx) {
+ DynTypedNodeList Parents = Ctx.getParents(E);
+ while (Parents.size() == 1) {
+ const auto *S = Parents[0].get<Stmt>();
+ if (!S)
+ return nullptr;
+ if (!isa<ExprWithCleanups, ParenExpr>(S))
+ return S;
+ Parents = Ctx.getParents(*S);
+ }
+ return nullptr;
+}
+
+InefficientContainerAssignmentCheck::InefficientContainerAssignmentCheck(
+ StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ ContainerClasses(utils::options::parseStringList(Options.get(
+ "ContainerClasses", "::std::vector;::std::deque;::std::list;"
+ "::std::forward_list;::std::basic_string"))) {}
+
+void InefficientContainerAssignmentCheck::storeOptions(
+ ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "ContainerClasses",
+ utils::options::serializeStringList(ContainerClasses));
+}
+
+void InefficientContainerAssignmentCheck::registerMatchers(
+ MatchFinder *Finder) {
+ if (ContainerClasses.empty())
+ return;
+
+ const auto Container = cxxRecordDecl(hasAnyName(ContainerClasses));
+ const auto Temporary =
+ cxxConstructExpr(hasDeclaration(cxxConstructorDecl(ofClass(Container))))
+ .bind("ctor");
+
+ // Match: lhs = Container(...) and lhs = Container{...}, where the assignment
+ // is the container's own 'operator='. Template instantiations are skipped:
+ // the rewrite might not fit every instantiation, and the temporary is only
+ // visible where the types are known.
+ Finder->addMatcher(
+ cxxOperatorCallExpr(
+ unless(isInTemplateInstantiation()), hasOverloadedOperatorName("="),
+ callee(cxxMethodDecl(ofClass(Container))),
+ hasArgument(0, expr().bind("lhs")),
+ hasArgument(1, ignoringImplicit(anyOf(
+ Temporary, cxxFunctionalCastExpr(has(
+ ignoringImplicit(Temporary)))))))
+ .bind("op"),
+ this);
+}
+
+void InefficientContainerAssignmentCheck::check(
+ const MatchFinder::MatchResult &Result) {
+ const auto *Op = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("op");
+ const auto *LHS = Result.Nodes.getNodeAs<Expr>("lhs");
+ const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructExpr>("ctor");
+ ASTContext &Ctx = *Result.Context;
+
+ // The rewrites call members of the destination, so the temporary must have
+ // exactly the destination's type; a derived class or another specialization
+ // would go through a different 'operator='.
+ if (!ASTContext::hasSameUnqualifiedType(LHS->getType(), Ctor->getType()))
+ return;
+
+ const CXXConstructorDecl *CtorDecl = Ctor->getConstructor();
+ SmallVector<const Expr *, 4> Args;
+ for (const Expr *Arg : Ctor->arguments())
+ if (!isa<CXXDefaultArgExpr>(Arg))
+ Args.push_back(Arg);
+
+ // 'lhs = Container();' releases the storage rather than reusing it, which is
+ // usually the point; 'clear()' would keep the capacity.
+ if (Args.empty())
+ return;
+
+ // 'assign' has no allocator parameter.
+ if (Args.size() >= 2 && passesAllocator(*CtorDecl, Args.size(), Ctx))
+ return;
+
+ Rewrite Form = Rewrite::Assign;
+ const InitListExpr *InitList = nullptr;
+ if (const auto *StdInitList =
+ dyn_cast<CXXStdInitializerListExpr>(Args[0]->IgnoreParenImpCasts());
+ StdInitList && Args.size() == 1) {
+ Form = Rewrite::InitList;
+ InitList =
+ dyn_cast<InitListExpr>(StdInitList->getSubExpr()->IgnoreImplicit());
+ } else if (Args.size() == 1) {
+ if (CtorDecl->isCopyOrMoveConstructor()) {
+ if (!ASTContext::hasSameUnqualifiedType(Args[0]->getType(),
+ LHS->getType()))
+ return;
+ Form = Rewrite::Direct;
+ } else if (CtorDecl->getParamDecl(0)
+ ->getType()
+ .getNonReferenceType()
+ ->isIntegralOrEnumerationType()) {
+ Form = Rewrite::ClearResize;
+ } else {
+ // A conversion from another type: the temporary is the conversion
+ // itself, and removing it is a different transformation.
+ return;
+ }
+ } else if (isFromRangeTag(CtorDecl->getParamDecl(0)->getType())) {
+ if (Args.size() != 2)
+ return;
+ Form = Rewrite::AssignRange;
+ }
+
+ llvm::SmallPtrSet<const ValueDecl *, 4> LHSDecls;
+ collectReferencedDecls(*LHS, Ctx, LHSDecls);
+ const auto MentionsDestination = [&](const Expr *Arg) {
+ return refersToAnyOf(*Arg, Ctx, LHSDecls);
+ };
+
+ // 'x = Container(x);' copies a container into itself to trim its capacity;
+ // that temporary is the point rather than waste.
+ if (Form == Rewrite::Direct && MentionsDestination(Args[0]))
+ return;
+
+ // 'assign' must not be given iterators, pointers or elements that refer into
+ // the container it replaces. Counts and other arithmetic values are computed
+ // before the call and are harmless.
+ const bool AliasesDestination = llvm::any_of(Args, [&](const Expr *Arg) {
+ return !Arg->getType()->isArithmeticType() && MentionsDestination(Arg);
+ });
+
+ // 'assign', 'clear' and 'resize' do not yield the container, so those
+ // rewrites need the value of the assignment to be discarded.
+ const Stmt *Parent = getEnclosingStatement(*Op, Ctx);
+ const bool ValueDiscarded =
+ isa_and_nonnull<CompoundStmt, IfStmt, WhileStmt, DoStmt, ForStmt,
+ CXXForRangeStmt, CaseStmt, DefaultStmt, LabelStmt,
+ AttributedStmt>(Parent);
+ const bool OwnStatement = isa_and_nonnull<CompoundStmt>(Parent);
+
+ std::optional<std::string> Replacement;
+ if (!Op->getBeginLoc().isMacroID() && !Op->getEndLoc().isMacroID()) {
+ bool Rewritable = true;
+ switch (Form) {
+ case Rewrite::Assign:
+ case Rewrite::AssignRange:
+ Rewritable = ValueDiscarded && !AliasesDestination;
+ break;
+ case Rewrite::ClearResize:
+ // Two statements, in which the destination is named twice and the
+ // count is evaluated after 'clear()'.
+ Rewritable = OwnStatement && !LHS->HasSideEffects(Ctx) &&
+ !Args[0]->HasSideEffects(Ctx) &&
+ !MentionsDestination(Args[0]);
+ break;
+ case Rewrite::InitList:
+ // The initializer list is materialized before the assignment.
+ Rewritable = InitList != nullptr;
+ break;
+ case Rewrite::Direct:
+ break;
+ }
+
+ if (Rewritable) {
+ const auto GetText = [&](SourceRange R) {
+ return Lexer::getSourceText(CharSourceRange::getTokenRange(R),
+ *Result.SourceManager, getLangOpts());
+ };
+ const StringRef LHSText = GetText(LHS->getSourceRange());
+ bool Valid = !LHSText.empty();
+ SmallVector<StringRef, 4> ArgTexts;
+ for (const Expr *Arg : Args) {
+ ArgTexts.push_back(GetText(Arg->getSourceRange()));
+ Valid = Valid && !ArgTexts.back().empty();
+ }
+ const std::string Dest =
+ needsParens(*LHS) ? ("(" + LHSText + ")").str() : LHSText.str();
+ if (Valid) {
+ switch (Form) {
+ case Rewrite::Assign:
+ Replacement = Dest + ".assign(" + llvm::join(ArgTexts, ", ") + ")";
+ break;
+ case Rewrite::AssignRange:
+ Replacement = Dest + ".assign_range(" + ArgTexts[1].str() + ")";
+ break;
+ case Rewrite::ClearResize:
+ Replacement =
+ Dest + ".clear(); " + Dest + ".resize(" + ArgTexts[0].str() + ")";
+ break;
+ case Rewrite::InitList: {
+ const StringRef ListText = GetText(InitList->getSourceRange());
+ if (!ListText.empty())
+ Replacement = (LHSText + " = " + ListText).str();
+ break;
+ }
+ case Rewrite::Direct:
+ Replacement = (LHSText + " = " + ArgTexts[0]).str();
+ break;
+ }
+ }
+ }
+ }
+
+ const auto Diag =
+ diag(Op->getOperatorLoc(),
+ "inefficient assignment from a temporary '%0'; "
+ "%select{use 'assign'|use 'assign_range'|use 'clear' and 'resize'|"
+ "assign the initializer list directly|assign the source directly}1 "
+ "to reuse the existing storage")
+ << CtorDecl->getParent()->getQualifiedNameAsString()
+ << static_cast<int>(Form);
+ if (Replacement)
+ Diag << FixItHint::CreateReplacement(Op->getSourceRange(), *Replacement);
+}
+
+} // namespace clang::tidy::performance
diff --git a/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h
new file mode 100644
index 0000000000000..7468b683f4cfe
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/InefficientContainerAssignmentCheck.h
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include <vector>
+
+namespace clang::tidy::performance {
+
+/// Finds assignments of a freshly constructed temporary container to a
+/// container of the same type and suggests the `assign` member function, or
+/// an equivalent in-place rewrite, that reuses the existing storage.
+///
+/// For the user-facing documentation see:
+/// https://clang.llvm.org/extra/clang-tidy/checks/performance/inefficient-container-assignment.html
+class InefficientContainerAssignmentCheck : public ClangTidyCheck {
+public:
+ InefficientContainerAssignmentCheck(StringRef Name,
+ ClangTidyContext *Context);
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+ bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+ return LangOpts.CPlusPlus;
+ }
+
+private:
+ const std::vector<StringRef> ContainerClasses;
+};
+
+} // namespace clang::tidy::performance
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_INEFFICIENTCONTAINERASSIGNMENTCHECK_H
diff --git a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
index 9eee02494be91..6115b9aad0f51 100644
--- a/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
@@ -14,6 +14,7 @@
#include "ForRangeCopyCheck.h"
#include "ImplicitConversionInLoopCheck.h"
#include "InefficientAlgorithmCheck.h"
+#include "InefficientContainerAssignmentCheck.h"
#include "InefficientStringConcatenationCheck.h"
#include "InefficientVectorOperationCheck.h"
#include "MoveConstArgCheck.h"
@@ -50,6 +51,8 @@ class PerformanceModule : public ClangTidyModule {
"performance-implicit-conversion-in-loop");
CheckFactories.registerCheck<InefficientAlgorithmCheck>(
"performance-inefficient-algorithm");
+ CheckFactories.registerCheck<InefficientContainerAssignmentCheck>(
+ "performance-inefficient-container-assignment");
CheckFactories.registerCheck<InefficientStringConcatenationCheck>(
"performance-inefficient-string-concatenation");
CheckFactories.registerCheck<InefficientVectorOperationCheck>(
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index 6fe497e5f6eaf..50987c3464c1c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -113,6 +113,13 @@ infrastructure are described first, followed by tool-specific sections.
Finds calls to `value_or` (and alternative spellings `valueOr`,
`ValueOr`) on optional types where the return type is expensive to copy.
+- New {doc}`performance-inefficient-container-assignment
+ <clang-tidy/checks/performance/inefficient-container-assignment>` check.
+
+ Finds assignments of a freshly constructed temporary container to a container
+ of the same type, such as `v = std::vector<int>(n, 0);`, and suggests
+ `assign` or an equivalent in-place rewrite that reuses the existing storage.
+
- New {doc}`portability-avoid-pragma-comment
<clang-tidy/checks/portability/avoid-pragma-comment>` check.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.md b/clang-tools-extra/docs/clang-tidy/checks/list.md
index 5a220b13eb599..fa653744676ea 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.md
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.md
@@ -357,6 +357,7 @@ readability/*
| {doc}`performance-for-range-copy <performance/for-range-copy>` | Yes |
| {doc}`performance-implicit-conversion-in-loop <performance/implicit-conversion-in-loop>` | |
| {doc}`performance-inefficient-algorithm <performance/inefficient-algorithm>` | Yes |
+| {doc}`performance-inefficient-container-assignment <performance/inefficient-container-assignment>` | Yes |
| {doc}`performance-inefficient-string-concatenation <performance/inefficient-string-concatenation>` | |
| {doc}`performance-inefficient-vector-operation <performance/inefficient-vector-operation>` | Yes |
| {doc}`performance-move-const-arg <performance/move-const-arg>` | Yes |
diff --git a/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md b/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md
new file mode 100644
index 0000000000000..81e92efedadfe
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-container-assignment.md
@@ -0,0 +1,89 @@
+```{title} clang-tidy - performance-inefficient-container-assignment
+```
+
+# performance-inefficient-container-assignment
+
+Finds assignments of a freshly constructed temporary container to a container
+of the same type, such as `v = std::vector<int>(n, 0);`, and suggests the
+`assign` member function or an equivalent in-place rewrite. The temporary
+allocates its own buffer, and the move assignment then discards the buffer the
+destination already owns. `assign` writes into the existing buffer and only
+allocates when the new contents do not fit.
+
+```cpp
+std::vector<int> v;
+std::string s;
+
+v = std::vector<int>(n, 0); // fix-it: v.assign(n, 0);
+v = std::vector<int>(first, last); // fix-it: v.assign(first, last);
+v = std::vector<int>{1, 2, 3}; // fix-it: v = {1, 2, 3};
+v = std::vector<int>(n); // fix-it: v.clear(); v.resize(n);
+v = std::vector<int>(other); // fix-it: v = other;
+s = std::string(n, ' '); // fix-it: s.assign(n, ' ');
+s = std::string(str, pos, count); // fix-it: s.assign(str, pos, count);
+```
+
+A brace...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/222159
More information about the cfe-commits
mailing list