performance-inefficient-vector-operation

查找可能低效的 std::vector 操作(例如 push_backemplace_back),这些操作可能会导致不必要的内存重新分配。

它还可以查找在循环中将元素添加到 protobuf 重复字段的调用,而没有在循环之前调用 Reserve()。先调用 Reserve() 可以避免不必要的内存重新分配。

目前,该检查只检测以下类型的循环,这些循环具有单语句体

std::vector<int> v;
for (int i = 0; i < n; ++i) {
  v.push_back(n);
  // This will trigger the warning since the push_back may cause multiple
  // memory reallocations in v. This can be avoid by inserting a 'reserve(n)'
  // statement before the for statement.
}

SomeProto p;
for (int i = 0; i < n; ++i) {
  p.add_xxx(n);
  // This will trigger the warning since the add_xxx may cause multiple memory
  // reallocations. This can be avoid by inserting a
  // 'p.mutable_xxx().Reserve(n)' statement before the for statement.
}
std::vector<int> data;
std::vector<int> v;

for (auto element : data) {
  v.push_back(element);
  // This will trigger the warning since the 'push_back' may cause multiple
  // memory reallocations in v. This can be avoid by inserting a
  // 'reserve(data.size())' statement before the for statement.
}

选项

VectorLikeClasses

以分号分隔的类似向量类名称的列表。默认情况下,只考虑 ::std::vector

EnableProto

当为 true 时,该检查还会针对 proto 重复字段的低效操作发出警告。否则,该检查只会针对低效的向量操作发出警告。默认值为 false