Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst

raw
1 .. title:: clang-tidy - performance-enum-size
2
3 performance-enum-size
4 =====================
5
6 Recommends the smallest possible underlying type for an ``enum`` or ``enum``
7 class based on the range of its enumerators. Analyzes the values of the
8 enumerators in an ``enum`` or ``enum`` class, including signed values, to
9 recommend the smallest possible underlying type that can represent all the
10 values of the ``enum``. The suggested underlying types are the integral types
11 ``std::uint8_t``, ``std::uint16_t``, and ``std::uint32_t`` for unsigned types,
12 and ``std::int8_t``, ``std::int16_t``, and ``std::int32_t`` for signed types.
13 Using the suggested underlying types can help reduce the memory footprint of
14 the program and improve performance in some cases.
15
16 For example:
17
18 .. code-block:: c++
19
20 // BEFORE
21 enum Color {
22 RED = -1,
23 GREEN = 0,
24 BLUE = 1
25 };
26
27 std::optional<Color> color_opt;
28
29 The `Color` ``enum`` uses the default underlying type, which is ``int`` in this
30 case, and its enumerators have values of -1, 0, and 1. Additionally, the
31 ``std::optional<Color>`` object uses 8 bytes due to padding (platform
32 dependent).
33
34 .. code-block:: c++
35
36 // AFTER
37 enum Color : std:int8_t {
38 RED = -1,
39 GREEN = 0,
40 BLUE = 1
41 }
42
43 std::optional<Color> color_opt;
44
45
46 In the revised version of the `Color` ``enum``, the underlying type has been
47 changed to ``std::int8_t``. The enumerator `RED` has a value of -1, which can
48 be represented by a signed 8-bit integer.
49
50 By using a smaller underlying type, the memory footprint of the `Color`
51 ``enum`` is reduced from 4 bytes to 1 byte. The revised version of the
52 ``std::optional<Color>`` object would only require 2 bytes (due to lack of
53 padding), since it contains a single byte for the `Color` ``enum`` and a single
54 byte for the ``bool`` flag that indicates whether the optional value is set.
55
56 Reducing the memory footprint of an ``enum`` can have significant benefits in
57 terms of memory usage and cache performance. However, it's important to
58 consider the trade-offs and potential impact on code readability and
59 maintainability.
60
61 Enums without enumerators (empty) are excluded from analysis.
62
63 Requires C++11 or above.
64 Does not provide auto-fixes.
65
66 Options
67 -------
68
69 .. option:: EnumIgnoreList
70
71 Option is used to ignore certain enum types. It accepts a
72 semicolon-separated list of (fully qualified) enum type names or regular
73 expressions that match the enum type names. The default value is an empty
74 string, which means no enums will be ignored.