Java – Best Way to Store List as Constant

java

Let's say I want to parse some JSON and I store the path in a Java constants class the path that I want to follow.

For example:

public static final List<String> path = Arrays.asList("a", "b", "c"); 

so that I can do this (pseudocodeish):

public boolean checkSomething() {
    JsonThing json = ...
    for (String path : Constants.path) {
        json.get(path);
    }

    return json.getAsString().equals("value");
}

Would it be better to store this constant as a String like:

public static final String path = "a:b:c";

and then do:

public boolean checkSomething() {
    JsonThing json = ...
    for (String path : Constants.path.split(":") {
        json.get(path);
    }
    return json.getAsString().equals("value");
}

Since the path is already stored in memory, would it be more efficient to just keep a : separated list since that String will take up less space than the array. In this instance, there's a little more work to be done (iterating over String to turn it into list), but then the list is garbage collected when the method is over.

Best Answer

The difference in memory consumption of a List of Strings compared to a concatenated String should be meaningless. Choose the data structure that best suits the functional needs.

It's very likely a List object wrapping an array of Strings, which is what Arrays.asList("a", "b", "c") produces, is a good choice. A concatenated String, on the other hand, is rarely a good choice as a data structure.

However, if memory consumption is a real issue, which could be true if you need to hold millions of such paths, then you could consider alternatives. I have to say it's hard to imagine such case if your data consists of JSON paths. It smells like a serious design issue that should be solved on pen and paper before trying to fix it by optimizing at code level.

String itself is not an optimal way to store character data that makes uses of a very limited subset of Unicode. If I had to hold an enormous chunk of character data in memory, I would first look into encoding the character data efficiently instead of using Strings.

Related Topic