[clang-format] Use std::iota and reserve when sorting Java imports. NFC.
authorMarek Kurdej <marek.kurdej+llvm.org@gmail.com>
Tue, 1 Feb 2022 13:29:31 +0000 (14:29 +0100)
committerMarek Kurdej <marek.kurdej+llvm.org@gmail.com>
Tue, 1 Feb 2022 13:29:31 +0000 (14:29 +0100)
This way we have at most 1 allocation even if the number of includes is greater than the on-stack size of the small vector.

clang/lib/Format/Format.cpp

index 9611e4a..dd4755c 100644 (file)
@@ -2749,13 +2749,16 @@ static void sortJavaImports(const FormatStyle &Style,
   unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
   if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
     return;
+
   SmallVector<unsigned, 16> Indices;
+  Indices.resize(Imports.size());
+  std::iota(Indices.begin(), Indices.end(), 0);
+
   SmallVector<unsigned, 16> JavaImportGroups;
-  for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
-    Indices.push_back(i);
-    JavaImportGroups.push_back(
-        findJavaImportGroup(Style, Imports[i].Identifier));
-  }
+  JavaImportGroups.reserve(Imports.size());
+  for (const JavaImportDirective &Import : Imports)
+    JavaImportGroups.push_back(findJavaImportGroup(Style, Import.Identifier));
+
   bool StaticImportAfterNormalImport =
       Style.SortJavaStaticImport == FormatStyle::SJSIO_After;
   llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {