Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jvm optimisations for string variables in methods

In a project that I am maintaining, I found a java class with a method "fn" similar to one shown below

class Test{

public void fn(){
    String METHOD_NAME = "fn";
    ...
    sysout("In " + METHOD_NAME);
}
}

The program runs indefinitely and the method 'fn' is called continuosly and at very high frequency. The question is

  1. would the variable METHOD_NAME get created every time fn() is called?
  2. would the JVM do some optimization so that the variable METHOD_NAME is not garbage collected and reused the next time fn() is called?
  3. would there a performance improvement if I made the variable a public static final?
    (Actually there are so many such functions that I want to know if its worth it to change all of them)

(I guess the string pool plays some role here)

Thanks, Kiran Mohan

like image 539
Kiran Mohan Avatar asked Dec 28 '22 22:12

Kiran Mohan


2 Answers

Yes, the variable METHOD_NAME will be created each time you enter the method, but that's a very, very cheap operation (in fact creating 2 variables is as expensive as creating 1).

The value (i.e. the String object) "fn" will not be recreated, but will come from the constant string pool.

However, the expression "In " + METHOD_NAME will be recomputed and cause a new String object to be created each time, because it is not a compile time constant expression.

If METHOD_NAME where static final, then that expression as well would be a compile time constant and thus would come from the constant pool.

like image 75
Joachim Sauer Avatar answered Jan 08 '23 20:01

Joachim Sauer


Variables aren't garbage collected - objects are.

"fn" is a string literal, so it will be interned. It won't be garbage collected (at least while that ClassLoader is alive; not sure whether there's one intern pool per CL or one for the whole JVM, but it's probably irrelevant) and the same string object will be used on every invocation.

If you make it a public static final there would definitely be an improvement, as the concatenation can be done by the compiler instead of at execution time.

If you make it final within the method (i.e. still as a local variable), that may have the same effect - I'm not sure.

like image 33
Jon Skeet Avatar answered Jan 08 '23 18:01

Jon Skeet