0

I learned that String literals are not always garbage collected, so I wonder whether or not those two code examples are comparative in case of performance?

length() just returns the size of the internal character array of a String, so as long a String is not newly created, there is no computation needed.

// example 1
private static final int BAR_LENGTH = "bar".length();
public int foo() {
   return BAR_LENGTH;
}

// example 2
public int foo() {
   return "bar".length();
}
Community
  • 1
  • 1
Journeycorner
  • 2,474
  • 3
  • 19
  • 43
  • Maybe I'm interpreting the code a bit too literally here, but example 2 would be obviously worse in performance because it makes a new `String` "bar" every time `foo()` is called. – Zircon Jul 18 '16 at 14:03
  • 3
    No difference. If you check length just returns you length property of character array with which string is backed by. – SMA Jul 18 '16 at 14:03
  • 3
    @Zircon - It doesn't create a new string each time. The JLS guarantees that the "bar" literal is represented by one and only one object. – Stephen C Jul 18 '16 at 14:05
  • @Zircon: Not regarding to the answer in the link under "learned": "Probably not. The code objects will contain one or more references to the String objects that represent the literals. So as long as the code objects are reachable, the String objects will be to." – Journeycorner Jul 18 '16 at 14:05
  • If the compiler is decent enough both methods would be optimized to plainly return 3 since the result can't change. So they should be equal performance wise and even if there was a difference you'd probably not notice it. – Thomas Jul 18 '16 at 14:09

2 Answers2

3

String literals are saved in a string pool. Thus in both cases above, the string won't be recreated it would be fetched from the pool. Therefore there is no difference in performance.

yamenk
  • 46,736
  • 10
  • 93
  • 87
  • Does this mean that any String declared inside an accessible method will remain in memory as long the program ends? – Journeycorner Jul 18 '16 at 14:12
  • 1
    Yes. And accessible means that the string is reference in the compiled code. The only case I know where a string literal is GCed is when the class was dynamically loaded and the class loader is destroyed – yamenk Jul 18 '16 at 14:19
2

I don't think it will make any difference.

This is what the implementation of length method from String (Here's the JavaDoc) class looks like :

  public int length()
  {
    return this.value.length;
  }

So essentially, it would return the length of the array value (defined as private final char[] value;) holding the characters of your string. And length is itself a property of array.

Abubakkar
  • 15,488
  • 8
  • 55
  • 83