Debian Codegraph @

llvm-project/clang-tools-extra/docs/clang-tidy/checks/performance/inefficient-vector-operation.rst

raw
1 .. title:: clang-tidy - performance-inefficient-vector-operation
2
3 performance-inefficient-vector-operation
4 ========================================
5
6 Finds possible inefficient ``std::vector`` operations (e.g. ``push_back``,
7 ``emplace_back``) that may cause unnecessary memory reallocations.
8
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.
12
13 Currently, the check only detects following kinds of loops with a single
14 statement body:
15
16 * Counter-based for loops start with 0:
17
18 .. code-block:: c++
19
20 std::vector<int> v;
21 for (int i = 0; i < n; ++i) {
22 v.push_back(n);
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.
26 }
27
28 SomeProto p;
29 for (int i = 0; i < n; ++i) {
30 p.add_xxx(n);
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.
34 }
35
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``:
40
41 .. code-block:: c++
42
43 std::vector<int> data;
44 std::vector<int> v;
45
46 for (auto element : data) {
47 v.push_back(element);
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.
51 }
52
53
54 Options
55 -------
56
57 .. option:: VectorLikeClasses
58
59 Semicolon-separated list of names of vector-like classes. By default only
60 ``::std::vector`` is considered.
61
62 .. option:: EnableProto
63
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`.