Search code examples
javastringperformancestring-pool

Java Strings: private static vs local variable performance


Is there any performance benefit by using a private final static String in java vs using a local string variable that has to get "initialized" every time the method is accessed?

I do think that using private static final strings is a good practice for constants that get reused in different parts of a class, however if a string were to be used only in one method, in one location, for a very specific reason that no other method is concerned about, I actually prefer to keep the class' internal interface clean with less private members, and just use a local variable.

Given that java has String interning, and actually keeps a pool with a single copy of each string that gets declared using quotes (String s = "some string"), would there actually be a performance hit from having to declare / initialize / assign the variable each time the method is accessed vs using a static string?

To make it a bit more clear, would there be any difference between using SS or LS?

class c {
private final static String SS = "myString";

  private void method(){
     //do something with SS
  }

  private void OtherMethod(){
     String LS = "myOtherString"
     //do same thing with LS
  }
}

Solution

  • Using a named constant is likely to be better for maintainability. However constants known at compile time can be used as inline in which case there is unlikely to be any difference.

    Note: if you are using a String literal, this will be created just once, no matter where in the JVM it is used.

    In this case the only difference is using a local variable on the stack which is unlikely to be any more expensive than a constant which have been used as inline.

    would there actually be a performance hit from having to declare the variable each time the method is accessed

    As Java uses a static compiler, a variable is only declared once (or once for each stage of compilation), when loading the class/method, regardless of how many times the methods is called. The variable might be initialized each time however.