Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Strings: private static vs local variable performance

Tags:

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   } } 
like image 620
Francisco Noriega Avatar asked Mar 23 '16 18:03

Francisco Noriega


2 Answers

Using a named constant is likely to be better for maintainability. However constants known at compile time can be inlined 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 be any more expensive than a constant which have been inlined.

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 initialised each time however.

like image 111
Peter Lawrey Avatar answered Oct 18 '22 12:10

Peter Lawrey


The truth is, at the end, there is no difference. A constant string in a local variable will still end up in the constant pool and optimized. So generally speaking, local variables are faster because they are easier to access, but in the case of constant strings it does not make a difference. So choose whatever is more readable and intuitive in your case.

like image 38
loonytune Avatar answered Oct 18 '22 13:10

loonytune