brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.5 KiB · b763113 Raw
75 lines · plain
1.. title:: clang-tidy - performance-enum-size2 3performance-enum-size4=====================5 6Recommends the smallest possible underlying type for an ``enum`` or ``enum``7class based on the range of its enumerators. Analyzes the values of the8enumerators in an ``enum`` or ``enum`` class, including signed values, to9recommend the smallest possible underlying type that can represent all the10values of the ``enum``. The suggested underlying types are the integral types11``std::uint8_t``, ``std::uint16_t``, and ``std::uint32_t`` for unsigned types,12and ``std::int8_t``, ``std::int16_t``, and ``std::int32_t`` for signed types.13Using the suggested underlying types can help reduce the memory footprint of14the program and improve performance in some cases.15 16For example:17 18.. code-block:: c++19 20    // BEFORE21    enum Color {22        RED = -1,23        GREEN = 0,24        BLUE = 125    };26 27    std::optional<Color> color_opt;28 29The `Color` ``enum`` uses the default underlying type, which is ``int`` in this30case, and its enumerators have values of -1, 0, and 1. Additionally, the31``std::optional<Color>`` object uses 8 bytes due to padding (platform32dependent).33 34.. code-block:: c++35 36    // AFTER37    enum Color : std::int8_t {38        RED = -1,39        GREEN = 0,40        BLUE = 141    }42 43    std::optional<Color> color_opt;44 45 46In the revised version of the `Color` ``enum``, the underlying type has been47changed to ``std::int8_t``. The enumerator `RED` has a value of -1, which can48be represented by a signed 8-bit integer.49 50By 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 the52``std::optional<Color>`` object would only require 2 bytes (due to lack of53padding), since it contains a single byte for the `Color` ``enum`` and a single54byte for the ``bool`` flag that indicates whether the optional value is set.55 56Reducing the memory footprint of an ``enum`` can have significant benefits in57terms of memory usage and cache performance. However, it's important to58consider the trade-offs and potential impact on code readability and59maintainability.60 61Enums without enumerators (empty) are excluded from analysis.62 63Requires C++11 or above.64Does not provide auto-fixes.65 66Options67-------68 69.. option:: EnumIgnoreList70 71    Option is used to ignore certain enum types. It accepts a72    semicolon-separated list of (fully qualified) enum type names or regular73    expressions that match the enum type names. The default value is an empty74    string, which means no enums will be ignored.75