How much memory do Enums take?

后端 未结 12 1261
野性不改
野性不改 2020-12-13 06:13

For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++

相关标签:
12条回答
  • 2020-12-13 06:20

    In ISO C++ there is no obligation for an enum to be larger than its largest enumerator requires. In particular, enum {TRUE, FALSE} may have sizeof(1) even when sizeof(bool)==sizeof(int). There is simply no requirement. Some compilers make the enums the same size as an int. That is a compiler feature, which is allowed because the standard only imposes a minimum. Other compilers use extensions to control the size of an enum.

    0 讨论(0)
  • 2020-12-13 06:23

    bool might be implemented as a single byte, but typically in a structure it would be surrounded by other elements that have alignment requirements that would mean that the boolean would effectively be occupying at least as much space as an int.

    Modern processors load data from main memory as a whole cache line, 64 bytes. The difference between loading one byte from L1 cache and loading four bytes is negligible.

    If you're trying to optimise for cache lines in a very high-performance application, then you might worry about how big your enum is, but generally I'd say it's clearer to define an enum than to use a boolean.

    0 讨论(0)
  • 2020-12-13 06:24

    In C++ an enum is typically the same size as an int. That said it is not uncommon for compilers to provide a command line switch to allow the size of the enum to be set to the smallest size that fits the range of values defined.

    0 讨论(0)
  • 2020-12-13 06:25
    printf("%d", sizeof(enum));
    
    0 讨论(0)
  • 2020-12-13 06:29

    No, an enum is generally the same size as an int, same as boolean.

    0 讨论(0)
  • 2020-12-13 06:30

    In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.

    0 讨论(0)
提交回复
热议问题