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
}
}
String.intern()
) are"quoted"
constants in your code. Strings constructed at runtime are not interned in the constants pool. – Glycol