Java Creating string with constant value inside function

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).

Jon Skeet
people
quotationmark

In both cases, these are constant variables as defined in JLS 4.12.4. So not only are the strings "doSomethingmetrics" and "saySomethingmetrics" interned, but so are "Metrics for doSomethingmetricsis something" and "Metrics for saySomethingmetricsis something". (Yeah, you need to add a space before "is".)

The first version logically has a slightly smaller stack, but I'd expect the JIT to optimize that away anyway.

I would use whichever form you find most readable. If you want to know for sure about the performance in your particular app, then as ever, the right thing to do is test both ways.

Looking at the results of javap -v, it looks like the second method actually has a slight advantage in that the unconcatenated strings don't even need to appear in the constant pool, as there's no way of reaching them. So you should see your class file being ever-so-slightly smaller that way. But again, I very much doubt that it'll make any difference.

people

See more on this question at Stackoverflow