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
(I guess the string pool plays some role here)
Thanks, Kiran Mohan
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With