Which one is better?
public class A {
private static final String DOSOMETHING_METRICS = "doSomethingmetrics";
private static final String SAYSOMETHING_METRICS = "saySomethingmetrics";
public void doSomething() {
...
System.out.println("Metrics for " + DOSOMETHING_METRICS + "is something");
}
public void saySomething() {
...
System.out.println("Metrics for " + SAYSOMETHING_METRICS + "is something");
}
}
OR
public class A {
public void doSomething() {
final String DOSOMETHING_METRICS = "doSomethingmetrics";
...
System.out.println("Metrics for " + DOSOMETHING_METRICS + "is something");
}
public void saySomething() {
final String SAYSOMETHING_METRICS = "saySomethingmetrics";
...
System.out.println("Metrics for " + SAYSOMETHING_METRICS + "is something");
}
}
I think Method 1 wins in case of memory optimization as compiler allocated memory only once and the garbage collector doesn't need to deallocate the string created in every function call. However, I think good coding practice recommends that variable should be bound to the scope in which it has to be used and constants should be defined as close as to they first use in the program which is where Method 2 wins.
What is your take on this? Which aspect is more important? The functions here will be called multiple times (let's say at least 100K times).