Java Strings: private static vs local variable performance

Viewed 5344

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
  }
}
3 Answers

I guess creating constants comes from old time when creating statics helped in maintaining only one string as part of the class in the jvm, rather than the object which gets created and garbage collected every time the object is created and destroyed. But with spring default scope as singleton rather than prototype, I guess it makes no difference. So, yeah, it depends how the class will be used, is the answer.

Related