Home > Enterprise >  Are inner enums efficient?
Are inner enums efficient?

Time:07-06

Quite often I see people using inner enums, for example:

public class Person {
  enum Gender {
    MALE,
    FEMALE,
    OTHER
  }
  ...
}

I am unsure how it works internally, so I am wondering whether there will be new instances of this enum class each time someone creates a new person, such as new Person()?

Will the inner enum keep costing more memory or will there only be a single one?

CodePudding user response:

Explanation

Nested enums are essentially static nested classes. They do not belong to instances of the outer class.

Regardless of how many persons you create, you will always only have a single enum Gender floating around, thats it.

Same goes for its values, there are only 3 values of this enum - regardless of how many persons you create.

Inner classes

However, even if you have an inner (non-static) class, such as

class A {
  class B { ... }
  ...
}

You will only have a single class B in memory (as you worded it). There is essentially always just a single class.

Now, when you create instances of B, you will have to create them based on a previously created instance of A, since instances of B now belong to instances of A and can only exist within their context.

Therefore, they also share non-static properties of that particular A instance. You will often see that being used for Iterator implementations of data-structures.

Static nested vs decoupled

If you have a static nested class, such as

class A {
  static class B { ... }
}

you might ask what the only real difference to actually fully decoupling them, as in

class A { ... }
class B { ... }

would be that the nesting makes clear that they somehow belong to each other, topic-wise. An example would be the Entry class in Map.


Notes on efficiency

You should actually stop bothering about efficiency on those minor things. Instead, think about readability for readers.

Efficiency, in the way you have in mind, is rarely ever a factor. And if, usually only in a very small spot in the whole code base (which is usually identified using a profiler).

So basically, unless you have a really good reason to not, always strive for the most readable and understandable solution.

CodePudding user response:

I think is not a matter o efficiency in terms of cost but there are some advantages of using enum.

  • Type Safety is one of the main advantages. When a method receives an enum, the compiler will check that the enum value is one of the values defined at the enum class; otherwise, if we give a String or an int constant to a method, the compiler will only check that this is a string or an int.
  • Another advantage is that enums, as they are a class, can have methods defined which may be useful.
  • We can also avoid NullpointerException errors when comparing enum values using == because the compiler is comparing values. I hope it helps.
  • Related