For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++
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.
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.
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.
printf("%d", sizeof(enum));
No, an enum is generally the same size as an int, same as boolean.
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.