Artemio Ramirez Artemio Ramirez - 9 months ago 48
Java Question

Is using enums efficient for many constants memory-wise?

I have a class that looks something like this:

public class MessageBuilder{

private enum MsgCodes{

CODE_1("some string"),
CODE_2("another string"),
CODE_3("you get the idea");

private String msg;

MsgCodes(String msg){
this.msg = msg;

private String text(){
return msg;

private MessageBuilder(){
//prevents initialization outside the class

//Gives synchronized behaviour to initialization without enforcing it into getInstance()
private static class Loader{
static MessageBuilder INSTANCE = new MessageBuilder();

public static MessageBuilder getInstance(){
return Loader.INSTANCE;

public String buildMessage(String[] codes){
String res = "";
for(String code : codes){
res += QAmsg.valueOf(code).text();
return res;


My concern is that overtime (meaning as the application develops) I will have more and more
on this class (which I understand is not only a good but even the preferred way to keep constants used on only one class), I'm rather new to
so I don't really know what will happen if this list becomes "too big" would this still be an efficient way to keep them?

Is there a different approach I could use so not the entire list but just the one code I'm using at the time gets instantiated? Would the
instances only one time or is it instancing everything every time I use them?

I made the class a singleton thinking this would prevent me from having the
list instantiated more than once, but this might be unnecessary as I don't fully understand


Enum members are just public static final constants, therefore singletons. Let's suppose your list grows to 10,000 enum members and that each costs 1 KB. Even under these extravagant assumptions it will amount to 10 MB of Java heap.

So clearly, you should not worry about the memory consumption of enum members.