1 .. title:: clang-tidy - performance-inefficient-vector-operation
3 performance-inefficient-vector-operation
4 ========================================
6 Finds possible inefficient ``std::vector`` operations (e.g. ``push_back``,
7 ``emplace_back``) that may cause unnecessary memory reallocations.
9 It can also find calls that add element to protobuf repeated field in a loop
10 without calling Reserve() before the loop. Calling Reserve() first can avoid
11 unnecessary memory reallocations.
13 Currently, the check only detects following kinds of loops with a single
16 * Counter-based for loops start with 0:
21 for (int i = 0; i < n; ++i) {
23 // This will trigger the warning since the push_back may cause multiple
24 // memory reallocations in v. This can be avoid by inserting a 'reserve(n)'
25 // statement before the for statement.
29 for (int i = 0; i < n; ++i) {
31 // This will trigger the warning since the add_xxx may cause multiple memory
32 // reallocations. This can be avoid by inserting a
33 // 'p.mutable_xxx().Reserve(n)' statement before the for statement.
36 * For-range loops like ``for (range-declaration : range_expression)``, the type
37 of ``range_expression`` can be ``std::vector``, ``std::array``,
38 ``std::deque``, ``std::set``, ``std::unordered_set``, ``std::map``,
39 ``std::unordered_set``:
43 std::vector<int> data;
46 for (auto element : data) {
48 // This will trigger the warning since the 'push_back' may cause multiple
49 // memory reallocations in v. This can be avoid by inserting a
50 // 'reserve(data.size())' statement before the for statement.
57 .. option:: VectorLikeClasses
59 Semicolon-separated list of names of vector-like classes. By default only
60 ``::std::vector`` is considered.
62 .. option:: EnableProto
64 When `true`, the check will also warn on inefficient operations for proto
65 repeated fields. Otherwise, the check only warns on inefficient vector
66 operations. Default is `false`.