Search code examples
javamemorymicro-optimization

Is it more efficient to return a string literal or a const string in each subtype in Java?


I'm newish to Java but having coded in similar languages before I feel I should know the answer to this but there are things in Java (e.g. generics) that are counterintuitive so hopefully someone can enlighten me in this case.

If I have a base class and two implementations with overrides to use a different string, is it more performant to define a class const for each sub class or is it just the same to directly return a string literal in the overridden method? Is a new string allocated for each instance in the "run" case below?

public abstract class OpBase {
    
     protected abstract String getOpType();

     public WriteOpType(){
          Logger.info(getOpType());
     }
    public class WalkOperation extends OpBase {
    
        protected String getOpType() {
            return "walk";
        }
    }

or

public class RunOperation extends OpBase {
    private static final String OP_TYPE_RUN = "run";
    
     protected String getOpType() {
          return OP_TYPE_RUN;
     }
}

Solution

  • If you have String literals in your code, just like return "walk";, then these Strings will be internalized and handled just as if you had declared a 'constant' String.

    So there is no difference performance-wise.

    Also, this 'String variable' will always point to the exact same Object in memory, so even a == comparison on two results of that same function would yield true. (Except that you should never do == on strings, rather use string1.equals(string) for comparison)